0

I declare a property in my class: NSMutableArray *data;

classmethod{
  [self.data addObject: message];
}

It's adding the reference of message to the array, when the method ends, data's content would set to nil, is there a way I can do deep copy then add message to the array without losing it when the method ends.

user2735868
  • 83
  • 1
  • 1
  • 4
  • This may be related: http://stackoverflow.com/a/647532/335858 – Sergey Kalinichenko Jun 06 '14 at 15:09
  • 1
    What is `classmethod`, really? Is it a class method? (Does it begin with `+`?) If so, realize that `self` is a pointer to the class itself, not an instance of the class. It would help if you'd post your **actual code** -- what you have isn't valid Objective-C. – Caleb Jun 06 '14 at 15:09

3 Answers3

0

Like Caleb states, if this is truly a class method like your code insinuates then it wont work. If it is an instance method, like example 1 then it should work fine, and more code will be needed to help answer the question.

Example 1: This is ok

-(void)classMethod
{
    [self.data addObject: message];
}

Example 2: This is NOT ok because you can't reference properties from the class method unless you pass them

+(void)classMethodWithMessage:(NSString *)message
{
    [self.data addObject: message];
}

Example 3: This is ok because you pass the array that needs updating

+(void)classMethodWithArray:(NSMutableArray *)array message:(NSString *)message
{
    [array addObject: message];
}
hybrdthry911
  • 1,259
  • 7
  • 12
-1

You can add a copy of an object with:

[self.data addObject: [message copy]];

Though I'm unsure why you're losing your object, assuming self.data is a strong reference, it should keep message alive.

Lord Zsolt
  • 6,492
  • 9
  • 46
  • 76
  • I didn't down-vote, but whoever did needs to leave a comment as to "Why". One of the most annoying things is to down-vote without explaining why. – LJ Wilson Jun 06 '14 at 15:14
  • Who said anything about singletons, and why would it matter if the class were a singleton? – Caleb Jun 06 '14 at 15:14
  • The singleton design patter is the only one I've used where I expect a class method to modify a property, though I've removed that part of the answer. – Lord Zsolt Jun 06 '14 at 15:17
-1

The properties of message should be set "Strong"!

user2735868
  • 83
  • 1
  • 1
  • 4