iphone - iOS - 如何正确访问数组中的对象属性?

标签 iphone ios properties nsarray ivar

设置:
ViewController持有 MyArray来自 PersonClass 的对象.PersonClass只有两个属性:nameage .

问题:

当我想读出 name MyArray 中第一个对象的属性这样做的正确方法是什么?

我是否必须临时创建 PersonClass 的实例?像这样?

PersonClass *tmp = [PersonClass alloc] init];
tmp = [MyArray objectAtIndex:0];

NSLog(@"%@", tmp.name);

或者我可以直接引用propertiesobjectsMyArray ?

像这样的东西:
 NSLog(@"%@", [self.contactsArray objectAtIndex:0].name); // not working

最佳答案

我强烈建议使用

[(PersonClass *)[MyArray objectAtIndex:0] name]

而不是看似干净,但麻烦的形式
[[MyArray objectAtIndex:0] name]

有两个原因。首先,对于读者来说,在哪个对象上调用了什么是明确的。其次是编译器显式 - 如果两个方法共享相同的名称,但返回值不同,事情会变得很糟糕。 Cocoa With Love 的 Matt Gallagher 拥有 excellent explanation of this issue.

关于iphone - iOS - 如何正确访问数组中的对象属性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11969610/

相关文章:

ios - 使用 NSDictionary 对 UITableview 中的数据进行排序

ios - 在 Xcode 中验证资源并为 iOS 应用程序生成 getter 代码

iphone - iPhone 应用程序的界面 Photoshop 尺寸

iphone - 有人使用将外部页面加载到应用程序中的 iPhone 应用程序吗?

iphone - 在后台使用 NSOperationQueue 按时间顺序执行 AFHTTPClient 请求

python-3.x - 在父类(super class)中缓存属性

java - 如何在类(class)之间获取配置文件?

iphone - 如何在没有 .nib 文件的情况下创建 opengl iPhone 应用程序?

ios - 我在 UITableView 中添加了一个 View ,并且该 View 和第一个单元格之间存在间隙。我怎样才能删除它?

objective-c - BOOL 的@property setter