xcode basic explanation needed - ios

I am actually a newby at xcode. I can make out a few things be myself but have questions about what some things do and why they are put there. I have tried to read many e-books, watched tutorials, but they never go into the basics, alway just say "Add this, Click here etc"
Could someone give me some answers to a few questions please.
Ok, I know an ios app is mostly made out of Views, views are controlled by controllers. Each controller has a header (.h) file and a module?class? file (.m). The .h file contains the declarations of variables and functions used in the .m file.
The whole app is controlled by a master "controller" called the "delegate".
Definitions in .h file may be for example an action IBAction or IBLabel or something.
What raises questions for me is for example these lines:
#class FlipsideViewController;
#protocol FlipsideViewControllerDelegate
- (void)flipsideViewControllerDidFinish:(FlipsideViewController *)controller;
#end
#interface FlipsideViewController : UIViewController
#property (nonatomic, assign) id <FlipsideViewControllerDelegate> delegate;
- (IBAction)done:(id)sender;
and why are sometimes in another view controller the delegate class loaded
#class MainViewController;
what does the following do, meaning what is the #interface declaration?
#interface flipAppDelegate : NSObject <UIApplicationDelegate>
what is
nonatomic, retain
sorry for asking really stupid questions, but every tutorial just skips these things.
I can follow a youtube video or a manual, but it doesn't teach me a lot...

Let me try to answer your questions, one at a time.
what is the #interface declaration?
The interface declares a class. By declaring a class, I mean it specifies the instance variables and private/public methods that it contains. Again, the header file only contains the declaration of the methods, and the implementation/body of the methods lies in the module class. So, here-
#interface FlipsideViewController : UIViewController
The class FlipsideViewController derives from/subclasses/extends UIViewController. i.e Is a type of UIViewController but adds its own features.
Similarly
#interface flipAppDelegate : NSObject <UIApplicationDelegate>
Subclasses NSObject and implements the UIApplicationDelegate protocol. A protocol is essentially a set of methods that a class promises to implement (although there can be optional methods).
why are sometimes in another view controller the delegate class loaded
The delegate pattern allows a class to delegate its work to another class that implements the delegate protocol. So, here, FlipsideViewController keeps an instance of the delegate object, so that its flipsideViewControllerDidFinish: can be called.
what is nonatomic, retain
It means that when you set a value to your instance variable, the value's refcount will be incremented and set to your variable. Also, it will not happen as an atomic operation. You need atomic only in a multi-threaded environment.
#synthesize is simply a shortcut to generate getters and setters for your variables.

You really need to read the Objective-C Programming Language from Apple. It's pretty brief, and runs down the basics of the architecture, concepts, and syntax.
To address, briefly, some specifics:
The #class directive is used to declare the name of a class without importing it's header file. It is often used in a .h file declaring a protocol, because a protocol has no implementation, it doesn't need to import the interfaces of other classes (their .h files).
A protocol is a way of declaring what methods and properties a class should have in order to "implement" the protocol.
#interface is used in an interface file (.h) to declare a class, meaning to describe the methods and properties it will have, the protocols it will implement, and the superclasses from which it will inherit. In your example, the class will be called flipAppDelegate, which inherits all of the methods and properties of the NSObject class, and which implements the UIApplicationDelegate protocol.
In your class (.m) file, you will define (with all your code) all of the methods and properties that you declared in your interface file. You include the methods and properties you declared yourself, and from the protocols you implement.
#synthesize is used in a class implementation file (.m) to "synthesize" --- that is, automatically create the code for --- all the properties you declared in your interface (.h) file. Since properties normally just need basic accessors (a "getter" that just returns the current value, and a "setter" that just sets the current value), using #synthesize is a shortcut to let the compiler create the variable to store the value, the getter method, and the setter method for you automatically.

Xcode = An IDE (Integrated Development Environment)
Objective-C = A Language
Cocoa Touch, Media FrameWork, Core FrameWork = Frameworks used in developing for iOS
I'd highly recommend starting by learning Objective-C. At least with a primer first:
https://developer.apple.com/library/ios/#referencelibrary/GettingStarted/Learning_Objective-C_A_Primer/_index.html
There's a wealth of tutorials and videos available from Apple for developers you might want to start on the developer portal.

Related

Difference between declaring instance variable in .h file and .m inside the #interface braces

If some one can brief on declaring instance variable inside .h file inside #interface braces and in .m file #interface braces. like this below
#interface ViewController : UIViewController { NSString *str ; }
#interface ViewController () { NSString *anotherStr ; }
Thx
There's even a third place where you can define instance variables: at the implementation statement:
#implementation ViewController { NSString *yetAnotherString; }
AFAIK, in the olden times you could only define the instance variables in the main interface. The other two places were added later. You can also mix them (as long as they have different names).
The advantage of defining the variables at #implementation and also the class extensions #interface ViewController () level (when done inside an .m file) is that you can hide implementation details from users of your API. In other words, if someone reads the .h file (s)he doesn't know about the variables. This makes the visible API cleaner and is also a concept called "information hiding" which is quite important in object oriented programming: don't expose too much implementation details so you can change the implementation without breaking code using the class.
Note that you can also define IBOutlet variables at all three levels and Interface Builder will detect and use them!
So when you're deciding where to define the variable you can simply ask yourself: Do other people need to see the variable when they see the .h file? IMHO this is only true when you need/want to make a variable #public. For all other cases, you can define them at the class extension or implementation level to make the API cleaner.
Whatever you declare in ViewControllerA.H is public. It means that other view controllers that contain the ViewControllerA object can access use the methods or variables directly. Whatever you declare in .M is private, other view controller can not access it immediately.
As for my own practice, most of the variable (I don't use much) or properties I declare in .M to prevent other view controller to access it directly. It is just like one concept in Object Oriented Programming - Data Encapsulation.
Note: Please be reminded that this should not be confused with #public, #protected, #private like DarkDust mentioned below. It will be another different topic.
In objective-C while you declare the member in .h file, it becomes visible to the other file when .h file is imported as header.
By default all member variables are private. So, user can not use them directly. But with methods of runtime.h and setValueForKey give them an alternate way to set those variable.
To avoid the user to do such mischief, its advisable to declare your private variables in .m file. They are called extensions as well.
For example you have created a variable in your appdelegate file. Now import appdelegate.h file to other .m file. Get the instance of appdelegate by sharedApplication delegate. Now you can set value by below way.
[appdelegate setValue:your_value forKey:#"name of variable"];
Though it was private, user could do so. Its because when you check for auto suggestion window, it will list down your private variable with strike through. To avoid getting those variable inside this window, it is advisable to declare them in .m file.

(Objective C) Do methods and variables need to be declared in head file(.h) if it is only used in its own class?

I have reviewed many code samples and have found that people commonly declare all methods and global variables in the header (.h) file. Is it necessary?
Methods to be used publicly (i.e. by classes other than the class implementing the method) and (truly) global variables should indeed be declared in the header file. The whole point is that you can import the header file in another source code file to gain access to the functionality declared there.
Methods that are meant to be private -- that is only to be called as part of the internal implementation of a class -- can be declared in a class extension. With recent versions of LLVM/Xcode, you actually don't even need to do that for non-#property methods. You can simply implement them and the compiler will be smart enough to see that they're there when called from other methods in the same class's implementation.
If you need to explicitly define a private ivar (rare these days), you can do so in a brace-enclosed section immediately after #implementation or #interface ClassName ().
In short: declare methods, functions, and variables that need be accessible from other classes in the .h file. Private methods and variable should be kept private by declaring them only in the .m file.
In recent versions of the SDK, you don’t have to declare methods that you only use internally to the class, so that can cut down clutter in your .h file. In general, the only methods, properties, and ivars that I put in my .h are the ones that I know other classes will need access to. That way, I never make the mistake of externally accessing a property that is supposed to be internal-only. The rest, I put in a class extension in the .m file like this:
#import "MyClass.h"
#interface MyClass ()
{
int _myIvar; // I rarely use these anymore,
// but if you want to use them, they go here.
}
#property (strong, nonatomic) NSArray *someArray;
#property (strong, nonatomic) NSDictionary *anotherProperty
#end
#implementation MyClass
#end
Header files have no special significance at all to the compiler. The preprocessor just copy-pastes them into the implementation file when you write #import anyway.

ARC clarification: Will my class extension properties be released automatically?

I'm new to ARC, and I have little question I didn't find info about.
I'm writing communication class and I want to add properties to a 3rd party class.
I wrote this code in my communicationClass.h:
#interface AFHTTPRequestOperation()
#property (nonatomic, assign) id<TargetProtocol> delegate;
#property (nonatomic, assign) SEL callback;
#property (nonatomic, retain) NSString *requestIdentifier;
#property (nonatomic, assign) int authenticationMode;
#end
The properties are added fine and I use them. My question is,
will ARC release these properties even if AFHTTPRequestOperation
is extended in a different file (my communicationClass.h)?
You are adding your additional properties using a class extension (not a category). Class extensions can only be used when you have access to the original source code for the class being extended. In this case you presumably have the source code for AFNetworking included in your project.
Apple's Programming with Objective-C has this to say about class extensions:
A class extension bears some similarity to a category, but it can only
be added to a class for which you have the source code at compile time
(the class is compiled at the same time as the class extension). The
methods declared by a class extension are implemented in the
#implementation block for the original class so you can’t, for
example, declare a class extension on a framework class, such as a
Cocoa or Cocoa Touch class like NSString.
and
Unlike regular categories, a class extension can add its own
properties and instance variables to a class. If you declare a
property in a class extension, [...] the compiler will automatically
synthesize the relevant accessor methods, as well as an instance
variable, inside the primary class implementation.
This would suggest that properties added by a class extension will function exactly the same as they would if they were in the original implementation file. However, the documentation suggests that the class extension should be compiled at the same time as the original implementation, I'm not clear how this happens if the communicationClass.h is not included in the original AFHTTPRequestOperation.m implementation file.
Given that the properties are working for you I would have to assume that the Objective-C Runtime is recognising them and this likely means that ARC will work correctly.
It is probably worth testing this. To check that ARC correctly releases the property I would add some logging to the dealloc method of a class that you are storing in a property added using this method. If the dealloc gets called when the parent is destroyed then you'll know it is working.
Yes your extension will be dealt by ARC.
You are not required to worry about it.
And it would look good if you use weak and strong in #property
I would say "Yes", they will be managed for you, and this based on this blog article that talks about how properties are managed in categories using objc_setAssociatedObject(). At the end of the article the author states:
Note: When class object(UIView object) is deallocated, its property
(animationIdentifer) will be sent a -release message automatically.
So I am assuming that ARC would do this for you. It's not very authoritative, I know...
The question is, if the AFHTTPRequestOperation class is compiled with ARC support. When the answer ist yes, than the ARC will handle this. Otherwise, it will not and the answer is no.
Another thing is that retain should be strong when using ARC.

Why are there two #interfaces for view controllers?

I'm learning some Objective-C, specifically iOS-related stuff. Whenever I generate a new UIViewController, or UITableViewController, etc, both the generated .h and .m files contain an #interface. The application will continue to compile if I delete the #interface from the .m file, also. What is the purpose of this #interface in the .m file?
The #interface in the .m file is a class extension (a category with no name). It's now in the templates to let you put any declaration of internal methods or ivars you don't want to expose to other parts of the code.
With the advent of the modern Objective-C runtime and the progress of clang, a well written class should:
1) have only public methods in the header
2) have ivars and internal methods declared in the internal class extension
Technically, it is a "class extension" (see ("Extensions" section of) the Objective-C intro docs). In practice, it has become common to use this as a "private" interface (it is only "visible" to the file in which it exists). Objective-C does not stop anyone else from calling these methods, but they won't "see" them (think of the .h file as your public interface and this anonymous category as your private interface).
It is handy for declaring #propertys which you don't want to expose publicly.

Declaring variables in .h file

Just wondering if its good programing practice to have a lot of variables declared in the .h file.
I'm writing my first app through which im learning xcode and obj-c. This ios app has just one xib, one .m and one .h file. I find my self a lot of times where i have a certain variable that i need to use in different methods/places in the .m file and i just end up declaring it in the .h file which seems like im making the variable global which i dont think is a good idea to have a lot of those.
Is this safe/ok to have a lot of variables declared in .h file or should i approach it in some other way?
Thanks
Is this safe/ok to have a lot of variables declared in .h file or
should i approach it in some other way?
It's absolutely OK to include a lot of variables in the .h! It just increases compile time a little and increases the size of your binary by an arbitrary amount. If it worries you, just split your implementation across a couple of categories.
I find my self a lot of times where i have a certain variable that i need to use in different methods/places in the .m file and i just
end up declaring it in the .h file which seems like im making the
variable global which i dont think is a good idea to have a lot of
those.
Variables that are accessed outside of one method should always be declared as iVars, and as properties if they require strong reference, or need to be accessed by outside classes. Global variables are way different, and you needn't worry about it.
Your .h file is the public interface of your class. It should only contain properties and methods that other classes need to know about.
You can declare ivars and internal methods and properties in a class continuation in the .m file (this is so common that one is now automatically included in the template for UIViewController subclasses).
You can also declare ivars within braces directly after the #implementation.
In iOS5, with ARC, declared ivars are strong references by default, so you don't have to use properties or accessor methods, but that choice depends on the rest of your class. For example, you may use lazy instantiation or perform other tasks or KVO when getting or setting a variable, in which case you'd always want to access it via a property or method, and if you're doing that for some ivars, and not others, it starts to look a bit messy.
It is alright for you to have many variables declared in the interface in the .h file when needed (as touched on by the other answers). But it would be wise for you to consider moving instance variables that do not need to be public into a category in the .m file. For example:
In the .h:
#import <Foundation/Foundation.h>
#interface SomeClass : NSObject {
NSDictionary *publicDict;
NSArray *privateArray;
}
#property (nonatomic, strong) NSDictionary *publicDict;
-(void)publicMethod:(id)anObj;
#end
And in the .m file:
#import "SomeClass.h"
#interface SomeClass () //Category that denotes private methods
#property (nonatomic, strong) NSArray *privateArray;
-(void)privateMethod;
#end
#implementation
#synthesize publicDict;
#synthesize privateArray;
-(id)init {
//...
}
-(void)publicMethod:(id)anObj {
//..
}
-(void)privateMethod {
//..
}
#end
This causes the compiler to issue a warning whenever any of the private methods contained in that category are accessed by outside classes. Additionally, this is the widely accepted way of adhering to an aspect of encapsulation in Objective-C.

Resources