xCode 4.6对象alloc和init

时间:2013-04-28 20:04:55

标签: nsobject xcode4.6

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

#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

1 个答案:

答案 0 :(得分: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风格的版本并自动保留。