【问题标题】:Ambiguity with Objective C PropertiesObjective C 属性的歧义
【发布时间】:2011-05-06 14:03:06
【问题描述】:

我在这里和其他论坛上遇到过很多关于 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"];

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

【问题讨论】:

    标签: iphone objective-c cocoa-touch properties


    【解决方案1】:

    如果您的 @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

    【讨论】:

    • Matt 的文章也提供了很好的见解。谢谢。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-06-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-09-05
    相关资源
    最近更新 更多