سؤال

I noticed that in some old versions of Xcode you could use properties of objects without self just fine. Now it gives me an error when I try to access my property without self, but today I'm writing this code, and it works fine, and doesn't give me any errors.

[aCoder encodeObject:itemName forKey:@"itemName"];

Why is it this way? Why don't I get an error in this case? Why is an error raised in other cases? Why can't this behavior be unified, and what should I use?

هل كانت مفيدة؟

المحلول

You have never been able to access properties without self. If you didn't use self, then you were directly accessing the instance variable that had the same name as the property. This has caused endless issues for many developers.

This is why the latest compilers (in the latest versions of Xcode) generate property ivars with a leading underscore. This way, if you forget to use self when trying to access the property, you get an error because there is no ivar with the same name.

To unify your experience you should use the following pattern with older compilers:

Define @property int foo;. Then define ivar int _foo. And then use @synthesize foo = _foo;.

With newer compilers you simply declare @property int foo and you are done. The compiler will generate the ivar int _foo for you.

In both cases you use self.foo for the property and _foo to directly access the ivar.

نصائح أخرى

Whenever you create a property with new LLVM compiler, it creates an ivar named _property .

If you don't over-ride the auto-synthesized then you need to use _property or self.property.

In your case it looks like you are using old compiler (i.e. coming with XCode4.3 bacwards) or you have over-riden auto-synthesized as:

@synthesize aCoder;

I assume you mean this warning:

enter image description here

A lot of projects do not enable many warnings in their build settings, so that could be one reason that you aren't seeing this warning.

There are also certain methods where it is common to access instance variables directly, and Xcode will ignore direct ivar access; these include init* and dealloc methods (but unfortunately not getter/setter methods).

If you define properties in a class and @synthesize them to use the same naming, then you can access them without self

e.g.

In .h

@property(nonatomic, copy) NSString *str1;

In .m

@synthesize str1 = str1;

str1 = @"hello";
self.str1 = @"hello"; // Or this

If you don't use explicit @synthesize, then XCode automatically does @synthesize property = _property (since recently) so you can do the following

In .h

@property(nonatomic, copy) NSString *str1;

In .m

_str1 = @"hello";
self._str1 = @"hello"; // Or this

You won't be able to use self if the property is defined in a parent class. You'll have to synthesize in your current class to be able to use it.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top