如何使用NSObject子类?

时间:2012-04-07 23:07:27

标签: iphone objective-c ios cocoa-touch

所以我创建了一个名为Query

的NSObject子类
@interface Query : NSObject

@property (nonatomic, assign) NSNumber *weight;
@property (nonatomic, assign) NSNumber *bodyFat;
@property (nonatomic, assign) NSNumber *activityLevel;

@end

这对于设置对象的属性是否正确?

在VC1中:

BodyFatViewController *aViewController = [[BodyFatViewController alloc]init];
aViewController.query = self.query;
[self.navigationController pushViewController:aViewController animated:YES];

在VC2中:

- (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component {
    Query *anQuery = [[Query alloc]init];
    anQuery.bodyFat = [self.bodyFatArray objectAtIndex:row];
    anQuery.weight = self.query.weight;
    self.query = anQuery;
}

3 个答案:

答案 0 :(得分:2)

在两个VC之间共享一个对象是完全自然的:

VC1中的

@property (strong, nonatomic) Query *query;
@synthesize query=_query;

// init it
self.query = [[Query alloc] init];
self.query.weight = [NSNumber numberWithInt:150];

// when it's time to present VC2:
BodyFatViewController *aViewController = [[BodyFatViewController alloc]init];
aViewController.query = self.query;
[self.navigationController pushViewController:aViewController animated:YES];

然后在VC2中:

// this is in the public interface in VC2.h
//
@property (strong, nonatomic) Query *query;

不要在VC2中分配/初始化它。 VC1做到了!! 但随意设置或覆盖值......

self.query.bodyFat = [NSNumber numberWithFloat:0.5];

答案 1 :(得分:1)

不要创建新查询只需使用属性:

self.query.bodyFat = [self.bodyFatArray objectAtIndex:row];

答案 2 :(得分:0)

是的,这是正确的。

self.query = newQueryObject

myBodyFatViewController.query = newQueryObject

两者都有效。