문제

I have an object Activity which has three NSString properties activityName, activityType, activityDescription

I want to do something like this

NSString *currentProperty = activity.activityDescription;
currentProperty = @"My description";

and make activity.activityDescription be automatically updated as I change currentProperty

I think it should be possible since I work with pointers, but in practice it doesn't work. What am I doing wrong?

도움이 되었습니까?

해결책

This is exactly what Key-Value Coding (KVC) was made for. Example:

NSString *currentKey = @"activityDescription";

NSString *oldDescription = [myActivity valueForKey:currentKey];
[myActivity setValue:@"My Description" forKey:currentKey];

You don't use a pointer (in the C sense of the word) but a key of type NSString. You can use KVC to get and set arbitrary properties of objects.

Apple's guide has all the details.

다른 팁

What you're talking about is the difference between:

  1. Pointers
  2. Pointers to pointers
  3. Object contents

To do what you're thinking about would be a pointer to a pointer (though you generally don't want to do that). What you have is a pointer (currentProperty). So, when you set currentProperty, all you're doing is replacing your local pointer contents with a different address.

Generally you should just set activity.activityDescription = ... directly, or, use an NSMutableString if you want to change the string contents, or, as per the answer from @NikolaiRuhe, use KVC (as that allows you to abstract away from what the current key is).

Well, you are not really working with pointers. activityDescription is a property, and a property is really the combination of two methods, a getter method named activityDescription and a setter method named setActivityDescription:. The thing that is the equivalent of a pointer is a "selector", type SEL. For example

SEL theSetter = @selector (setActivityDescription:);
[self performSelector:theSetter withObject:some string];

Or you can define a block, which is the equivalent of a pointer to arbitrary code.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top