2013-04-28 73 views
0

我是xcode的新手。我使用xCode 4.6,我不明白xcode如何完全实例化对象。 我认为,如果您声明对象作为.h文件中的属性,它会自动分配并初始化它。唯一可以让我的代码工作的方法是在属性文件上执行alloc和init。我在下面列出了我的示例代码,但是谁能告诉我这是否是正确的方法?xCode 4.6对象分配和初始化

#import <Foundation/Foundation.h> 

@interface Person : NSObject 

@property (nonatomic, strong) NSString *name; 
@property (nonatomic) int age; 

@end 

#import "Person.h" 

@implementation Person 

@end 

#import <UIKit/UIKit.h> 
#import "Person.h" 

@interface ViewController : UIViewController 

@property (strong, nonatomic) Person *person; 
@property (weak, nonatomic) IBOutlet UILabel *lblDisplay; 
- (IBAction)btnChangeLabel:(id)sender; 

@end 

#import "ViewController.h" 

@interface ViewController() 

@end 

@implementation ViewController 

- (void)viewDidLoad 
{ 
    [super viewDidLoad]; 
    // Do any additional setup after loading the view, typically from a nib. 
    _person = [[Person alloc]init]; 
} 

- (void)didReceiveMemoryWarning 
{ 
    [super didReceiveMemoryWarning]; 
    // Dispose of any resources that can be recreated. 
} 

- (IBAction)btnChangeLabel:(id)sender { 

    [_person setName:@"Rich"]; 
    [_person setAge:50]; 
    _lblDisplay.text = [NSString stringWithFormat:@"%@ is %d years old.",_person.name,_person.age]; 

} 
@end 

回答

0

你做正确的事,除非你btnChangeLabel方法,通过请参阅您的属性:

self.person.name = @"Rich"; 
self.person.age = 50; 
_lblDisplay.text = [NSString stringWithFormat:@"%@ is %d years old.",self.person.name,self.person.age]; 

您要使用的基础变量“_person”唯一的一次是什么时候需要为他们分配空间。剩下的时间,你会使用它们的访问器(getter和setter;这就是“self.person.name =”的事情)。这样编译器就会知道做ARC风格的发布并自动保留。

+0

非常感谢! – Rich 2013-04-28 20:13:05