简体   繁体   中英

private and public property in objective-C

So what is actually the difference between these two versions:

@interface Foo : NSObject
// A guy walks into a bar.
@property(nonatomic, copy) NSString *bar;
@end

// Implementation file
@interface Foo ()
@property(nonatomic, retain) NSArray *baz;
@end

and

@interface Foo : NSObject
// A guy walks into a bar.
@public
@property(nonatomic, copy) NSString *bar;

@private
@property(nonatomic, retain) NSArray *baz;
@end

As far as my understanding goes, putting the @property in the .m basically means that it is private. Correct me if I am wrong? Also which is the best implementation then? Is it just a coding style/practice?

The compiler can warn you about things that it knows about.

When I import your header the compiler can see that Foo has a method called bar and setBar: . This means I can use them both

[instanceOfFoo setBar:@"some string"];

NSLog(@"%@", [instanceOfFoo bar]);

whereas because I only imported the header - the compiler can only see the header it is not aware that there are also methods baz and setBaz: available, so doing the following will cause the compiler to barf

[instanceOfFoo setBaz:@"some string"];

NSLog(@"%@", [instanceOfFoo baz]);

I can however still access these properties if I know they exist by using KVC like this without the compiler barfing

[instanceOfFoo setValue:@"some string" forKey:@"baz"];

NSLog(@"%@", [instanceOfFoo valueForKey:@"baz"]);

You are correct in your understanding. Putting the @property in an @interface in the .m is making it "private". What that means is you'll get compiler warnings if you try to access that property from another class that includes the .h that doesn't include the @property declaration. This doesn't mean that you can't access the property, just that the compiler will yell at you.

As for best, neither one is best. You should implement the one that makes sense for you object, which could include items in both the .h and .m (read only proper in .h with full property in .m). Basically if the @property shouldn't ever be accessed outside of your class put it in the .m.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM