设置:ViewController
持有 MyArray
来自 PersonClass
的对象.PersonClass
只有两个属性:name
和 age
.
问题:
当我想读出 name
MyArray
中第一个对象的属性这样做的正确方法是什么?
我是否必须临时创建 PersonClass
的实例?像这样?
PersonClass *tmp = [PersonClass alloc] init];
tmp = [MyArray objectAtIndex:0];
NSLog(@"%@", tmp.name);
或者我可以直接引用
properties
的objects
在 MyArray
?像这样的东西:
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/