2015-07-09 42 views
1

我正试图学习如何在不使用预设方法的情况下更改对象的属性。这个例子只是一个例子。我知道有这种alertControllerWithTitle...重建方法,但我想直接与财产。Objective-C:以编程方式更改@property(不包含预先构建的方法)

- (IBAction)clickedButton:(id)sender { 
UIAlertController * view= [UIAlertController 
          alertControllerWithTitle:@"My Title" 
          message:@"Select you Choice" 
          preferredStyle:UIAlertControllerStyleActionSheet]; 

UIAlertAction* ok = [UIAlertAction 
        actionWithTitle:@"OK" 
        style:UIAlertActionStyleDefault 
        handler:^(UIAlertAction * action) 
        { 
         //Do some thing here 
         [view dismissViewControllerAnimated:YES completion:nil]; 

        }]; 
UIAlertAction* cancel = [UIAlertAction 
         actionWithTitle:@"Cancel" 
         style:UIAlertActionStyleDefault 
         handler:^(UIAlertAction * action) 
         { 
          [view dismissViewControllerAnimated:YES completion:nil]; 

         }]; 

[view addAction:ok]; 
[view addAction:cancel]; 
[self presentViewController:view animated:YES completion:nil]; 
} 

我想更新标题@property (nullable, nonatomic, copy) NSString *title;我该怎么做?

+3

既然告诉你简单地调用'view.title = @“New Title”;'看起来太明显了,你需要澄清你的问题。这里你不明白的是什么? – rmaddy

回答

1
view.title = @"The new title"; 

我觉得您的问题还有更多?目前还不清楚“预设方法”的含义。

1

我正试图学习如何更改对象的属性而不使用预设的方法。

所有的属性实在是,某些存取方法存在的诺言,无论他们是由编译器合成或由程序员提供。可能有也可能没有用于存储属性值的实际实例变量。

这听起来像你问如何直接更改伊娃,而不使用方法。如果你愿意,你当然可以这样做,提供财产的伊娃存在,你知道它的名字。对于合成属性,将会有一个名为与该属性相同但前缀为下划线的ivar,除非程序员在属性声明中指定了其他名称。换句话说:

@property int foo;  // ivar for foo is named _foo 
@property int bar; 
//... 
@synthesize bar = bar; // ivar for bar is named bar 

无论如何,如果你知道变量名,就可以直接或存取其值设置:

[self setFoo:10]; 
self.foo = 10; 
_foo = 10; 

这些都具有相同的效果,如果-setFoo:访问器的标准事情。但是,如果代码不是你的,你不能确定-setFoo:不只是设置变量_foo,所以你应该使用setter。

一般来说,最好使用访问器,除非有原因(例如在初始化器中)。