ARC pattern for pattern property initialization - ios

When I first read Beginning iOS 3 Development before ARC, I remember seeing patterns like this in some ViewController class:
.h
#property (nonatomic, retain) NSArray *myArray;
.m
in viewDidLoad:
NSArray *tempArray = [[NSArray alloc] init];
self.myArray = tempArray;
[tempArray release];
I remember reading that you did this so the properties could handle the memory for you if you used the property setters/getters. So now with ARC, I'm wondering if you still follow that kind of variable creation. For example, if you start a new project in iOS 6, in the AppDelegate, they do
.h
#property (strong, nonatomic) ViewController *viewController;
.m
self.viewController = [[ViewController alloc] initWithNibName:#"ViewController" bundle:nil];
The temp variable is not created in this case. I was wondering why and if I should be following that pattern instead of the first one. Thanks!

They are the same pattern except now ARC properly handles the release for you. The 2nd block of code is just fine with ARC. That's what makes ARC so nice.

Yes you should. ARC optimizes away the unnecessary retain and release automatically for you.

Related

how to have a NSString value in all classes?

I need to capture data in the viewController and stay stored during the execution of the app and you can use it in any other View that I have, try creating a NSString in AppDelegate as follows:
AppDelegate.h
property (Retain, nonatomic) NSString * token;
AppDelegate.m
synthesize token;
and then call it in the other class as follows
adding include
#include "AppDelegate"
creating an object
AppDelegate * theToken = [[AppDelegate allow] init];
label.text = theToken.token;
but not working me, in some ViewController appears nill
The problem is that you're creating a brand new instance of the AppDelegate instead of accessing the current one.
Instead of:
AppDelegate * theToken = [[AppDelegate alloc] init];
try this:
AppDelegate * theToken = (AppDelegate*)[[UIApplication sharedApplication] delegate];
Edit: As rmaddy and Louis Tur also pointed out in the comments, your use of retain and synthesize are pre-ARC relics.
"Strong" is the ARC equivalent of "retain" so you can update your property to the following in order to maintain a strong reference:
property (strong, nonatomic) NSString * token;
Furthermore, once upon a time (until some time post-ARC but pre-iOS6 if I remember correctly), synthesizing your .h properties in your .m was required. But in the modern era, it's generally good practice to leave out synthesize in your .m and instead access the property within AppDelegate.m using "self"; for example, self.token.

Access NSMutableArray from another class - Objective C

I have a main ViewController that contains a desginated class. Within that ViewController there is a Container that is linked to an embed ViewController. Within that embed ViewController I am creating an NSMutableArray. I am not trying to access that array inside the main ViewController. I know that if I use:
create_challenge_peopleSelect *myScript = [[create_challenge_peopleSelect alloc] init];
NSLog(#"%#",myScript.selectedCells);
The NSLog will output null because I am creating a new ViewController and that gets rid of the already set array. So my question is how can I access that array without overwriting it?
UPDATE:
Heres where the NSMutableArray is being created:
create_challenge_peopleSelect.h:
#property (strong, nonatomic) NSMutableArray *selectedCells;
create_challenge_peopleSelect.m:
if([selectedCells containsObject:label.text])
{
cell.accessoryType = UITableViewCellAccessoryNone;
[selectedCells removeObjectIdenticalTo:label.text];
}
else
{
cell.accessoryType = UITableViewCellAccessoryCheckmark;
[selectedCells addObject:label.text];
}
This class is the container class off the main ViewController
No I want to access the selectedCells within my main ViewController, I have been doing things such as:
create_challenge_peopleSelect *myScript = [[create_challenge_peopleSelect alloc] init];
I would prefer to stay away from the App Delegate If possible.
You seem to be unclear on the difference between classes and instances. OK, so, say we have two NSArrays:
NSArray *a = [[NSArray alloc] initWithObjects:#"hello", #"I", #"am", #"an", #"array", nil];
NSArray *b = [[NSArray alloc] initWithObjects:#"so", #"am", #"I", nil];
If I do a.count, I'll get 5 as the answer because the array contains five objects. Meanwhile, if I do b.count, I'll get 3, because that array contains three objects. It isn't that creating b "gets rid of the already set count". They are separate objects completely unrelated to each other.
Your view controller class is the same way. When you create a different instance, it doesn't overwrite the old one -- it's just not the same object. In order to use the original view controller object, you need to get a reference to it.
So how do you get a reference to it? Well, the general answer is you design your app so that the two objects know about each other. There are lots of specific ways to accomplish this. A lot of people will say "Just stick a reference in the app delegate." That is one thing you can do, but it's not always the best choice. It can get out of control if you just stick everything in your app delegate. Sometimes it's the right answer, often other things are the right answer. Another approach is to have an object that knows about both of those objects introduce them to each other. But sometimes there is no such object. So it's situational.
Basically, instead of creating a new view controller, you need to maintain a pointer to the original.
I suggest storing an instance of your UIViewController in the AppDelegate in order to retain the particular instance of the view controller you've created by making it a global variable.
ex. In the App Delegate.h
#import "ViewController.h"
#class ViewController;
#interface AppDelegate : UIResponder <UIApplicationDelegate>
#property (nonatomic) ViewController *viewController;
Then from whatever view controllers' .m's from which you need to read/write to the variable, create a pointer to the application's app delegate, ex:
#import "AppDelegate.h"
#interface WhateverViewController ()
AppDelegate *mainDelegate;
- (void)viewDidLoad {
mainDelegate = (AppDelegate*)[[UIApplication sharedApplication] delegate];
}
So wherever you first create that view controller in your code (before ever using it), initialize it using this global variable. ex. If you're using xibs:
mainDelegate.viewController = [[UIViewController alloc] initWithNibName:#"ViewController" bundle:nil];
[self.navigationController pushViewController:mainDelegate.viewController animated:YES];
ex. If you're using storyboards:
UIStoryboard *storyboard = [UIStoryboard storyboardWithName:#"StoryboardName" bundle:nil];
mainDelegate.viewController = [storyboard instantiateViewControllerWithIdentifier:#"viewControllerID"];
[self.navigationController pushViewController:mainDelegate.viewController animated:YES];
(This is assuming it's in a place other than the app delegate in which case the pointer to the App Delegate isn't needed.)
Then when accessing the array from another UIViewController use
mainDelegate.viewController.array
To access the NSMutableArray from one class to another class use following code.
In the first view controller in which u have declared the object of NSMutableArray, declare the property and synthesize for the same as below,
//In FirstViewcontroller.h class,
#property (nonatomic, strong) NSMutableArray *arrData;
//In FirstViewcontroller.m class
#synthesize arrData;
Also FirstViewcontroller object should be global so you can create the object of FirstViewcontroller in app delegate file.
//appdelegate.h
#property (nonatomic, strong) FirstViewcontroller *objFirst;
//appdelegate.m
#synthesize objFirst;
FirstViewcontroller *objFirst=[[FirstViewcontroller alloc]init];
Now in SecondViewcontroller in which you have to access array,
create the share object of Appdelegate file
//SecondViewcontroller.m
AppDelegate *app = (AppDelegate*)[[UIApplication sharedApplication] delegate];
Then use will get the required array as below,
app.objFirst.arrData
This is your required array I hope it will help you.
The basic idea here is that in your original class, the array is referred to by a pointer. Your original class would allocate it and presumably load it. Other parts of your program can be handed the contents of the property, which is a pointer, assign that to their own pointer holder, and use it as if you had declared it there. Please use the above code;
MyClass *aClass = [[MyClass alloc] initWithMyInitStuff];
NSMutableArray *ThatArray = aClass.MyArray;
NSLog("Count of ThatArray: %d", [That.Array count]);
What you've done in the code provided is set a public property for a mutable array...
#property (strong, nonatomic) NSMutableArray *selectedCells;
The NSMutableArray is not "created" by setting that property. At some point in your code you also have to create the NSMutableArray by initialising...
NSMutableArray *selectedCells = [[NSMutableArray alloc] init];
or by using a convenience method such as...
NSMutableArray *selectedCells = [NSMutableArray arrayWithCapacity:(NSUInteger)<initialising capacity>];
or
NSMutableArray *selectedCells = [NSMutableArray arrayWithArray:(NSArray *)<initialising array>];
Initialising an NSMutableArray is often done only once. If it is repeated, the contents are overwritten against the property used to point to the array. As such, a useful location for this is often within the viewDidLoad view controller lifecycle method.

Setting variable in another class in objective-c

I have a map-controller where the user can tab the map to add a new marker. The idea is then to store the coordinates in the new marker-class. The problem I am facing is setting those variables.
NewMarkerController.h
#interface NewMarkerController : UIViewController
{
NSNumber *posLat;
NSNumber *posLng;
}
#property (nonatomic, retain) NSNumber *posLat;
#property (nonatomic, retain) NSNumber *posLng;
#end
I am also synthesizing this in the .m file is that makes any difference.
MapController.m
NewMarkerController *vc = [[NewMarkerController alloc] init];
[vc posLat:coordinate.latitude];
The last line shows an error saying No visible #interface for 'NewMarkerController' declears the selector 'postLat', but...there is...?
Can anyone spot the problem I am having here?
[vc setPosLat:coordinate.latitude];
or
vc.posLat = coordinate.latitude;
This syntax:
[vc posLat:coordinate.latitude]
means that posLat is a function of the vc kind of class. As you want to set a variable, if you synthesized it you can just do:
[vc setPosLat:coordinate.latitude]
or
vc.posLat = coordinate.latitude

Memory management, things to be clear

I need to get things clear about Objective-C memory management:
If I declare an object in the class header as ivar without #property:
#interface MyFacebooDelegate : UIViewController
{
TableViewController *tableController;
}
...
#end
and some where in the code for example in - (void)viewDidLoad I do :
tableController = [[TableViewController alloc] init];
so where is best way to release it. What if I make the instant object a property what will be the different? and how the memory management will be too
#interface MyFacebooDelegate : UIViewController
{
TableViewController *tableController;
}
...
#end
#property (nonatomic, strong) TableViewController *tableController;
What the following syntax do exactly for the object viewController:
.h
#interface AppDelegate : UIResponder <UIApplicationDelegate>
#property (strong, nonatomic) ViewController *viewController;
#end
.m
#implementation AppDelegate
#synthesize window = _window;
#synthesize viewController = _viewController;
- (void)dealloc
{
[_window release];
[_viewController release];
[super dealloc];
}
.....
#end
If I want to return an object through a method to another class, do I need to autorelease it in the method body first and then retain it in receiver side?
for example this method what exactly to do in the method body and in the receiver side too:
-(NSString *)getFriendId
{
NSArray *ar = [NSArray arrayWithObjects:#"1",#"2",#"3", nil];
return [ar objectAtIndex:0];
}
I know this a lot but I am really confused and need your help.
1) best way is in dealloc; or right before re-setting it.
2) a property does the retain/release for you. But WARNING! You keep mixing up things. You use "strong" here, which relates to ARC. If you really insist on using classic retain/release (you shouldn't) then use (nonatomic, retain) instead.
3) Your properties get deallocated on dealloc. Again, strong is wrong here.
4) Yes. Ideally you should. Another reason why ARC is awesome, it does this all for you, automatically.
tl;dr: Use ARC. Never go back. (But still learn manual memory management)
ARC is the answer for your all memory management question. Very import note on Strong and Weak property in addition to ,
iOS Strong property: So strong is the same as retain in a property declaration before ARC. For ARC projects I would use strong instead of retain, I would use assign for C primitive properties.
iOS outlets should be defined as declared properties. Outlets should generally be weak, except for those from File’s Owner to top-level objects in a nib file (or, in iOS, a storyboard scene) which should be strong. Outlets that you create will therefore typically be weak by default, because: Outlets that you create to, for example, subviews of a view controller’s view or a window controller’s window, are arbitrary references between objects that do not imply ownership.

Access the value of text field from another class

I am making an app using a utility application template. I am trying to access the value of a UITextField from the FlipSideVewController class.
In the MainViewController.h file I have -
#interface MainViewController : UIViewController <UISplitViewControllerDelegate>{
UITextField *textField;
NSString *myText;
}
#property (retain, nonatomic) IBOutlet UITextField *textField;
#property (nonatomic, retain) NSString *myText;
-(IBAction)pressButton:(id)sender;
In the MainViewController.m file -
myText = [[NSString alloc] initWithFormat: textField.text];
NSLog(#"%#",myText);
I am creating the FlipSideViewController in the MainViewController class using the following code -
FlipsideViewController *controller = [[[FlipsideViewController alloc] initWithNibName:#"FlipsideViewController" bundle:nil] autorelease];
controller.delegate = self;
controller.modalTransitionStyle = UIModalTransitionStyleFlipHorizontal;
[self presentModalViewController:controller animated:YES];
This prints the value of the textfield in the console without any problems. The problem happens when I try to access the value of the textfield in the FlipSideVewController class (after the user presses the go button).
In the FlipViewController class I have -
MainViewController *obj = [[MainViewController alloc] init ];
NSString *abc = obj.textField.text;
NSLog(#"%#",abc);
The FlipSideVewController nib file is loaded fine without any problems. However the console output is (null) when in FlipSideVewController.
I will appreciate any help.
Thanks
If you use the Utility Xcode template, you should think of MainViewController and FlipSideVewController as given: the framework will instantiate them for you and make it available to the rest of the program as you define (either in your code or in IB). What I mean by this is that your line:
MainViewController *obj = [[MainViewController alloc] init ];
does not really do what you want.
In your case, what you seems to want is access a text field controlled by the existing MainViewController instance (the one that gives you the NSLog output correctly) from your other existing FlipSideVewController instance. This is a matter of "connectin" somehow those two controllers.
There are several ways to accomplish this. One is defining a "model" for your app and have it shared between the controllers. See also the Model-View-Controller pattern. A model is just a data structure that contains your "data"; you make that data structure available to both of your controllers. The easiest way to create such data structure and have it shared is through a singleton (I am not suggesting to use it as the best way, just noting that it is the easiest way, IMO).
Another, less clean way is passing a reference to MainViewController to FlipSideVewController and then accessing the text field through it. By example, you could define an ivar in your FlipSideVewController, then, where the two controllers are created, you do the assignment to the ivar.
You should go to your MainViewController and declare your textField as a property first and synthesize it, so you can access it using obj.textField. And if you have just created obj using alloc and init, you wont have any text in the textField instance Variable.
MainViewController.h
#property (retain) UITextField *textField;
MainViewController.m
#synthesize textField;
and you could use
myText=textField.text;
Now this should do it and you can access this textField by obj.textField in your other class. But you still wont get its value if you are initializing it in your other class because you will be creating a brand new obj whose textField.text will be blank( unless you have overrided its designated initializer to set the textField.text value).
Declare NSString *abc as instance variable
NSString *abc;
and then as property
#property (copy) NSString *abc;
#synthesize abc;
After you create your FlipSideViewController,
controller.abc=myText;
Remove the code where you create obj.
This will do it.

Resources