如何将 NSString 参数传递给函数?



我想初始化一个对象。问题是如何正确通过NSString。

目标代码:

#import "ClaseHoja.h"
@implementation ClaseHoja
@synthesize pares;
@synthesize nombre;
-(id)init
{
self=[super init];
if(self){
}
return self;
}
-(id)initWithValues:(NSString*)nom par:(int)par
{
if([super init]){
pares=par;
nombre=nom;
}
return self;
}

当我调用函数时,我这样做:

NSString *nombre="Hello";
int par=20;
ClaseHoja *ch = [ClaseHoja alloc] initWithValues:nombre par:numPares]];

我建议:

  1. 将缺少的@添加到@"Hello"并修复alloc/init通话中的[]

  2. 如果您使用的是 Xcode,我会让编译器为您合成属性。无需@synthesize。但是,如果您在其他平台上使用独立的 LLVM,则可能需要它,但按照惯例,您将指定带有前面_的 ivar 。

  3. 我将nombre定义为copy属性,并显式复制传递给init方法的nombre值。您不想冒着将NSMutableString传递给您的方法并在您不知情的情况下不知不觉地发生突变的风险。

  4. 我建议将initWithValues:par:重命名为initWithNombre:pares:,以消除对正在更新的属性的任何疑问。

  5. 您不需要没有参数init。您可以依靠NSObject提供的那个。

  6. 您通常会使用NSInteger而不是int

  7. 在自定义init方法中,您希望确保执行if ((self = [super init])) { ... }

因此:

// ClaseHoja.h
@import Foundation;
@interface ClaseHora: NSObject 
@property (nonatomic, copy) NSString *nombre;
@property (nonatomic) NSInteger pares;
- (id)initWithNombre:(NSString*)nombre pares:(NSInteger)pares;
@end

// ClaseHoja.m
#import "ClaseHoja.h"
@implementation ClaseHoja
// If you're using modern Objective-C compiler (such as included with Xcode), 
// you don't need these lines, but if you're using, for example stand-alone 
// LLVM in Windows, you might have to uncomment the following lines:
//
// @synthesize nombre = _nombre;
// @synthesize pares = _pares;
- (id)initWithNombre:(NSString*)nombre pares:(NSInteger)pares {
if ((self = [super init])) {
_pares = pares;
_nombre = [nombre copy];
}
return self;
}
@end

你会像这样使用它:

NSString *nombre = @"Hello";
NSInteger pares  = 20;
ClaseHoja *ch = [[ClaseHoja alloc] initWithNombre:nombre pares:pares];

你需要像这样传递。您错过的另一件事@字符串前的符号。

NSString *nombre = @"Hello"; int par=20;
ClaseHoja *ch = [[ClaseHoja alloc]initWithValues:nombre par:par];

最新更新