Reputation: 35933
I have a method that returns an object, like
- (myObject *) doStuff: (NSString *)x
This method creates an entry on an array and also returns the object created, so I can do other things with it after running the method, but at some point in my code I don't need the reference it returns, so, instead of using
myObj1 = [doStuff: myValue];
I just want to make it like
[doStuff: myValue];
Is it ok to do that? Will I have any problem like crash or the app becoming crazy? Is there other alternatives to make this?
Upvotes: 1
Views: 91
Reputation:
Objective-C is similar to C in this regard: you can always ignore values returned by functions/methods.
However, as in C, it is important to follow the semantics defined by the function or method. For instance, if a function/method returns a pointer and the caller is supposed to free the corresponding memory, the caller needs to store that pointer in a variable and then call free(variable). Similarly, if a function/method returns an Objective-C object that's owned by the caller, then the caller must either send -release or -autorelease to the returned object.
Upvotes: 4
Reputation: 22305
Of course. Methods don't have to return anything, it's completely optional. It's what the void
return type is for:
- (void)doStuff:(int)myValue;
Edited to add
If you want to only return something sometimes and the method normally returns an object, simply return nil
. You don't have to provide a receiver.
Upvotes: 1
Reputation: 12787
- (myObject *) doStuff: x
here you need to declare x type also.like
-(myObject *)doStuff:(NSString *)myValue;
then if you declare a return type for function then you must return a value otherwise make it void.
If you declare a return type then this is not neccessary to recieve that value in a variable but function must return the value.
And also you can set the arrays values in this method but declare array globally. One thing more if you make -(myObject *)doStuff:(NSString *)myValue;
then it needs a object to call, for same class use self. you cant call like this
[doStuff: myValue];
Upvotes: 1
Reputation: 6448
It should be ok if you guarantee that memory management within this doStuff method is self-sustained. (i.e. you use things like autorelease when allocating any new stuff with that method so memory won't leak)
Upvotes: 1