简体   繁体   English

如何使用 NSObject 子类?

[英]How to use NSObject subclass?

So I've created a subclass of NSObject called Query所以我创建了一个 NSObject 的子类,叫做Query

@interface Query : NSObject

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

@end

Is this correct for setting the object's property?这对于设置对象的属性是否正确?

In VC1:在 VC1 中:

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

In VC2:在 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;
}

It's perfectly natural to share an object between two VCs:在两个 VC 之间共享一个 object 是很自然的:

in VC1:在 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];

and then in VC2:然后在 VC2 中:

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

Don't alloc/init it in VC2.不要在 VC2 中分配/初始化它。 VC1 did that!! VC1 做到了! But feel free to set or overwrite values...但是可以随意设置或覆盖值...

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

Don't create a new query simply use the property:不要创建新查询,只需使用属性:

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

Yes, it is correct.是的,这是正确的。

self.query = newQueryObject

or要么

myBodyFatViewController.query = newQueryObject

Both work.两者都有效。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM