English 中文(简体)
目标-C的私有和公有私有财产
原标题:private and public property in objective-C

所以这两种版本之间有什么区别呢?

@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

@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 underst和ing 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?

最佳回答

编译者可以警告你 它知道的事情。

当我导入您的页眉时, 编译器可以看到 Foo 有一种叫做 bar setBar: 的方法。 这意味着我可以同时使用这两种方法。

[instanceOfFoo setBar:@"some string"];

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

虽然因为我只导入了页眉 - 汇编器只能看到页眉, 但不知道还有方法 baz setBaz: 可用, 因此, 这样做会使编译器吐出来 。

[instanceOfFoo setBaz:@"some string"];

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

然而,我仍然可以访问这些属性, 如果我知道它们存在的话, 使用 KVC 这样使用 KVC, 而不使用编译器吐

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

NSLog(@"%@", [instanceOfFoo valueForKey:@"baz"]);
问题回答

您的理解是正确的。 将@ property 放在 @ interface in. m 上的@ interface 正在使它成为“ 私人的 ” 。 这意味着, 如果您试图从另一类中获取该属性, 包括不包含@ property 声明的. h 。 这并不意味着您无法访问该属性, 只是因为编译者会对你大吼大叫 。

最好的是, 两者都不是最好的。 您应该执行一个对您对象来说是有道理的, 它可以包括. h 和. m 中的项目( 仅在.h 中读取, 并在.m 中读取全部财产 ) 。 基本上, 如果@ propherty 不应该在您的课外访问的话, 请把它放在. m 中 。





相关问题
List Contents of Directory in a UITableView

I am trying to list the contents of Ringtones directory in a TableView, however, I am only getting the last file in the directory in ALL cells, instead of file per cell. This is my code: - (...

iPhone NSUserDefaults persistance difficulty

In my app i have a bunch of data i store in the NSUserdefaults. This information consists of an NSObject (Object1) with NSStrings and NSNumbers and also 2 instances of yet another object (Object2). ...

Writing a masked image to disk as a PNG file

Basically I m downloading images off of a webserver and then caching them to the disk, but before I do so I want to mask them. I m using the masking code everyone seems to point at which can be found ...

Resize UIImage with aspect ratio?

I m using this code to resize an image on the iPhone: CGRect screenRect = CGRectMake(0, 0, 320.0, 480.0); UIGraphicsBeginImageContext(screenRect.size); [value drawInRect:screenRect blendMode:...

Allowing interaction with a UIView under another UIView

Is there a simple way of allowing interaction with a button in a UIView that lies under another UIView - where there are no actual objects from the top UIView on top of the button? For instance, ...

热门标签