I have a viewController with a property of NSInteger (or NSNumber), What I want to do is pass the integer to the child ViewController, do some change (maybe add by some number).
But when I use NSNumber as property in the parent and child controller and pass it by set property:
//parent and child property.
@property (nonatomic,strong) NSNumber *num;
//pass to the child
child.num = self.num;
//do some change in child
self.num = [NSNumber numberWithInteger:[self.num integerValue] + 1];
This cannot change the value of the parent , because NSNumber is readonly and in the child they alloc a new one, without change the value of the parent.
So:
How I can pass a NSInteger or NSNumber to the child ViewController and change the value in it, and when child is pop away, the parent controller get the change?
You are defining and assigning a new NSNumber in the following line:
self.num = [NSNumber numberWithInteger:[self.num integerValue] + 1];
You can't use this method because NSNumbers are immutable.
So self.num will point to another location different from parent's num
.
To avoid problems like this you can use delegate pattern or simply passing parent's viewController pointer to the child and changing its num
value.
For example:
Parent's Header:
@property (nonatomic,strong) NSNumber *num;
Child's Header:
@property (nonatomic,weak) parentViewControllerClass * parentClass;
Code:
self.parentClass.num = [NSNumber numberWithInteger:[self.parentClass.num integerValue] + 1];
P.S. You can check out how to define protocols here and here. With that you can implement the delegate pattern.