iphone - Objective C 属性的歧义

标签 iphone objective-c cocoa-touch properties

我已经了解了这里和其他论坛上提出的有关 Objective-C 中的 @property 的许多问题。但时不时就会出现一个问题..

我们需要 i-var 来支持属性吗?

请检查以下代码 -

RootViewController.h 文件:-

#import <UIKit/UIKit.h>

@interface RootViewController : UIViewController {

}

@property (nonatomic, retain) NSMutableArray *arrTest;

@end

RootViewController.m如下 -

#import "RootViewController.h"

@implementation RootViewController
@synthesize arrTest;

#pragma mark -
#pragma mark View lifecycle


- (void)viewDidLoad {
    [super viewDidLoad];

    self.arrTest = [[[NSMutableArray alloc] init] autorelease];

    [arrTest addObject:@"Object1"];
    [arrTest addObject:@"Object2"];
    [arrTest addObject:@"Object3"];
    [arrTest addObject:@"Object4"];
    [arrTest addObject:@"Object5"];

    NSLog(@"arrTest :- \n%@",arrTest);
    NSLog(@"self.arrTest :- \n%@",self.arrTest);


    [self.arrTest addObject:@"Object6"];
    [self.arrTest addObject:@"Object7"];
    [self.arrTest addObject:@"Object8"];
    [self.arrTest addObject:@"Object9"];
    [self.arrTest addObject:@"Object10"];

    NSLog(@"arrTest :- \n%@",arrTest);
    NSLog(@"self.arrTest :- \n%@",self.arrTest);

    // Uncomment the following line to display an Edit button in the navigation bar for this view controller.
    // self.navigationItem.rightBarButtonItem = self.editButtonItem;

}

如您所见,我尚未创建实例变量来支持该属性。

由此,我假设变量是内部创建的,因为我只需说即可访问它

[arrTest addObject:@"Blah Blah"];

如果是这样,那么如果我们要声明属性,为什么还需要创建实例变量呢?

最佳答案

如果您的@property声明引用了未声明的ivar,Objective-C运行时将为您动态合成ivar。

这要求您针对 iPhone OS 或 64 位 Mac OS X 进行编译。如果您想以 Mac OS X i386 或 PPC 为目标,则必须显式声明您的 ivars。

这里有一篇关于此的好文章。 http://cocoawithlove.com/2010/03/dynamic-ivars-solving-fragile-base.html

关于iphone - Objective C 属性的歧义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4122780/

相关文章:

objective-c - 向 NSImageView 添加图像?

IOS 可滑动欢迎屏幕

iphone - NSDictionary 中的键和值是有序的吗?

objective-c - 比较两个数组并将相等的对象放入新数组中

iphone - iOS 表单控件

iphone - ShareKit - 将链接图像发布到 facebook 墙上

ios - 如何使用 Swift 泛型传递类型并返回该类型的对象?

iphone - 在 iOS 3.2 (iPad) 中正确显示和关闭全屏 MPMoviePlayerController

iphone - 计算加速度(驾驶汽车)

iphone - Xcode - 手动加载 View Controller