2015-07-21 73 views
0

我目前正在尝试学习Objective C,并通过这种方式,面向对象的语言。功能和OOP返回

我从我写的类声明了变量,但是,我的函数太长了,我想要关闭这些代码。

我不知道返回如何与类一起工作,这是我的问题。

Grapejuice *juice; 
    juice = [[Grapejuice alloc] init]; 
    [juice setName:@"Grape juice"]; 
    [juice setOrderNumber:1000]; 
    [juice setPrice:1.79]; 

这是在我做的这几个对象主要的一部分,我怎么能做到这一点在单独的功能,并且还得到了这些信息这一新功能的重新使用以后(例如打印)? 不知道我是否清楚,但我昨天刚刚开始学习,仍然在基础上犹豫不决。

感谢兄弟们。

+0

'Grapejuice * make_juice(){return [[Grapejuice alloc] init]; }'? –

+0

关键是要将我给你的整个代码切割成一个分离的函数,而不仅仅是初始化行 – Xcrowzz

+0

是的,我明白了。我认为上面的例子已经足够了,但由于它显然不是,我似乎必须说明整件事情:'Grapejuice * make_juice(){Grapejuice * juice = [[Grapejuice alloc] init]; [juice setPrice:1.79];/*等* /返回果汁; }' –

回答

2

如果我理解正确,我相信你想要的是你的Grapejuice类的自定义“init”方法。

在Grapejuice.h,添加:

- (instancetype)initWithName:(NSString *)name orderNumber:(NSInteger)number price:(double)price; 

在Grapejuice.m,添加:

- (instancetype)initWithName:(NSString *)name orderNumber:(NSInteger)number price:(double)price { 
    self = [super init]; 
    if (self) { 
     _name = name; 
     _orderNumber = number; 
     _price = price; 
    } 

    return self; 
} 

然后使用你这样做代码:

Grapejuice *juice = [[Grapejuice alloc] initWithName:@"Grape Juice" orderNumber:1000 price:1.79]; 

请注意,您可能需要调整orderNumberprice参数的数据类型。我只是猜测。根据您为Grapejuice类中的相应属性指定的类型适当地调整它们。

+0

我今天回来说我做了一个自定义的init,它的工作原理很完美,昨天就明白了。谢谢你的帮助 ! 只是一件事,为什么我会使用NSInteger而不是标准的int? – Xcrowzz