简体   繁体   中英

How to use NSObject subclass?

So I've created a subclass of NSObject called 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:

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

In 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:

in 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:

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

Don't alloc/init it in VC2. VC1 did that!! 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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