0

I'm currently trying to learn Objective C and by this way, Oriented Object languages.

I'm declaring variables from a class I've written, but, my functions are way too long, and I'd like to cut that code off.

I do not know how the return works with classes and that's my problem.

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

This, is part of a main in which I'm doing this to several objects, how can I do that in a separated function, and still got these informations out of this new function to be re-used later (to be printed for example) ? Not sure if I'm clear but I've just started learning it yesterday, still hesitating on the basics.

Thanks homies.

3
  • Grapejuice *make_juice() { return [[Grapejuice alloc] init]; }? Commented Jul 21, 2015 at 16:10
  • The point is to cut the whole code I gave you onto a separated function, not just the initialization line Commented Jul 21, 2015 at 16:12
  • yeah, I understand. I thought the above example was enough, but since it apparently isn't, I seem to have to spell out the whole thing: Grapejuice *make_juice() { Grapejuice *juice = [[Grapejuice alloc] init]; [juice setPrice:1.79]; /* etc. */ return juice; } Commented Jul 21, 2015 at 16:24

1 Answer 1

2

If I understand you correctly, I believe what you want is a custom "init" method for your Grapejuice class.

In Grapejuice.h, add:

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

In Grapejuice.m, add:

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

    return self;
}

Then to use that code you do:

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

Please note that you may need to adjust the data types for the orderNumber and price parameters. I'm just guessing. Adjust them appropriately based on whatever type you specified for the corresponding properties you have on your Grapejuice class.

Sign up to request clarification or add additional context in comments.

1 Comment

I came back today to say that I did a custom init and it works perfectly, figured it out yesterday. Thanks for your help ! Just one thing, why would I use a NSInteger instead of a standard int ?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.