-2

我正在使用最新的 xcode。实现文件:SimpleCar.m:

#import "SimpleCar.h"

@implementation SimpleCar


// set methods
- (void) setVin: (NSNumber*)newVin {
[vin release];
vin = [[NSNumber alloc] init];
vin = newVin;
}
- (void) setMake: (NSString*)newMake {
[make release];
make = [[NSString alloc] initWithString:newMake];
}
- (void) setModel: (NSString*)newModel {
[model release];
model = [[NSString alloc] initWithString:newModel];
}
// convenience method
- (void) setMake: (NSString*)newMake
    andModel: (NSString*)newModel {
// Reuse our methods from earlier
[self setMake:newMake];
[self setModel:newModel];
}

//get methods
- (NSString*) make; {
return make;
}
- (NSString*) model;{
return model;
}
- (NSNumber*) vin;{
return vin;
}

-(void) dealloc
{
[vin release];
[make release];
[model release];
[super dealloc];
}
@end

接口文件:SimpleCar.h:

#import <Foundation/Foundation.h>

@interface SimpleCar : NSObject {
NSString* make;
NSString* model;
NSNumber* vin;

}
// set methods
- (void) setVin:   (NSNumber*)newVin;
- (void) setMake:  (NSString*)newMake;
- (void) setModel: (NSString*)newModel;
// convenience method
- (void) setMake: (NSString*)newMake
    andModel: (NSString*)newModel;
// get methods
- (NSString*) make;
- (NSString*) model;
- (NSNumber*) vin;

@end

当我键入“[vin release]、[model release]、[make release]”时,实现文件中出现错误,我无法运行程序。

4

1 回答 1

1

ARC 已打开,因此内存管理是自动的。

该类的现代定义将声明为:

 @interface SimpleCar : NSObject
 @property(copy) NSString *make;
 @property(copy) NSString *model;
 @property(copy) NSNumber *vin;

 - initWithMake:(NSString*)make model:(NSString*)model vin:(NSNumber*)vin;
 @end

并将实施为:

 @implementation SimpleCar
 - initWithMake:(NSString*)make model:(NSString*)model vin:(NSNumber*)vin
 {
     if (self = [super init]) {
         _make = [make copy];
         _model = [model copy];
         _vin = [vin copy];
     }
     return self;
 }
 @end

您通常不会实现像setMake:andModel:. 它只是增加了 API 占用空间,并没有真正以方便的方式购买太多东西。它还提出了诸如“当我观察到make或时会发生什么model?”之类的问题。

于 2013-05-12T22:02:36.070 回答