Custom Methods now defined by the cocoa library - ios

I was asked this question during a technical discussion and can't seem to find answer anywhere.
The problem:
If I wrote methods by extending a core class (Lets say NSArray) which didn't exists in iOS 5 but were introduced in iOS 6.
What would happen to my application in the app store when the user upgrades to iOS 6? Would it crash? Would it be refer to foundation class? Would the runtime point to my function and everything will continue to work same?
Eg.
iOS 5.0
PGMyArray : NSArray
- (NSString) info; // convert and concatenate each object of the array into a string.
Now in iOS 6.0, Apple introduced the method publicly as part NSArray
NSArray
- (NSString) info; // Does exactly same as my method
What would happen when user upgrades to iOS 6.0 and my application calls
PGMyArray *myArray = [[NSArray alloc] init];
[myArray info];
My intelligent guess is, it would still be calling to PGMyArray-> info (after looking up from virtual table). However, I wasn't told the right answer and its bothering me for weeks now.
Any explanation / help is appreciated.

As you know any subclass can override an existing method. Even here you will end up with calling your method. i.e. Overriding it.

That's why you shouldn't call it "info". You should use a three letter prefix (two letter prefixes are reserved by Apple), like abcInfo.

You are extending the NSArray class, it means that if you implement a info method, YOUR method will be called, because you are ovveriding the default info method.
It is the same when you implement some methods like the viewDidLoad method. You have to implement it like this:
- (void)viewDidLoad {
[super viewDidLoad];
// Your initialization
}
You have to call the super method because you are overriding it, meaning that the super class viewDidLoad method is not called anymore.

Related

super init returns nil

I have this case where I just Call the init of Class I made this class is subclass of NSObject.
- (instancetype)initArray
{
self = [super init];
if (self) {
//Do Some Logic
}
return self;
}
This is my Call from the App Delegate
CategoryLoader *categoryLoader = [[CategoryLoader alloc]initArray];
Whats driving me crazy is that:
Although it returns nil it goes into the if condition
It doesn't return nil on other computer with other Xcode
Please note that both Xcode's are 6.3
Solutions i tried:
Cleaned Cache of Xcode
Deleted the class and created a new one
Reinstalled Xcode
Here is a Screenshot of whats happening:
Any suggestions why could it be returning nil from NSObject and what can i do next ?
Thank you
NSObject’s implementation of init should never return nil. This is documented in the NSObject Class Reference: although slightly confusing, the key part is
The init method defined in the NSObject class does no initialization; it simply returns self.
If you are observing it retuning nil, either something is not setup how you expect (perhaps the class isn’t a direct subclass of NSObject), or you are somehow interpreting the results incorrectly, or there is something wrong at another level. The fact that you observe different results on different machines suggests it might be at another level, like Xcode, the operating system, or the hardware. I can’t help much there; try rebooting.
Also, your method ought to be named init not initArray. This is not a requirement but a very strong convention. You can read about Object Initialization in Apple’s Concepts in Objective-C Programming
Ok. That was the problem:
The the scheme was on Release Mode. In this case the watch window displays nil in most of the objects. When I printed the value of self on NSLog it printed its value. The only difference between me and the other Xcode was the scheme.
So the solution is to edit the scheme of the project to be debug.
Thank you for your support

Key Value Coding vs accessor methods in iOS

I'm trying to understand some theory part in Objective C related to KVC. Following is the example I've done.
I'm having class call Cookie and it has a property like below
#property NSString *name;
Next, I have another class call Person and it has following property
#property Cookie *cookie;
Inside Person implementation file
#import "Cookie.h"
- (id)init
{
self = [super init];
if (self) {
_cookie = [[Cookie alloc] init];
}
return self;
}
In my ViewContrtoller I can write following two options to get the same result.
Using KVC :
[me valueForKeyPath:#"cookie.name"]
Using accessor methods :
[[me cookie] name]
To write accessor method , I had to import the Cookie class but doesn't need when using KVC.
Apart from that, what are the benefit of using KVC instead or using accessor methods? Is there any performance issue or security issue or good coding practice or any other benefit?
One situation where i found KVC very handy was when i had to perform some kind of operation on a collection object such as finding the average of a particular value.Specifically I used KVC operators.
For example
[myDict valueForKey:#"gamePoints"] valueForKey:#"doubleValue"] valueForKeyPath:#"#max.self"];
This will help you find the maximum value for the property 'gamePoints' from among an array of dictionaries/ objects.
Here is an excellent article by Mattt Thompson
Hope this contributes to what you are looking for.
There's no particular benefit in this case to using KVC. In general, you should prefer to use the accessors or dot syntax (e.g. me.cookie.name) when you can.
KVC is for when the name of the property you want to access is dynamic. It's not known at compile time. It comes from data (including a NIB, in the case of bindings on OS X) or is computed.
According to the Apple Docs:
Though key-value coding is efficient, it adds a level of indirection that is slightly slower than direct method invocations. You should use key-value coding only when you can benefit from the flexibility that it provides.
But I think this is probably a little over-cautious; I doubt you need worry too much unless your app is very performance sensitive.
Beside the given answers (+1) you get the advantage of identifier completion in Xcode which reduces the probability of typos. Importing the class is a good strategy, if you use it semantically. Look at it as a "bill of things I use", which can be helpful for understanding your code.
Great place to use KVO is unit testing. When you have following class interface:
#interface ServerCommunicationManager : NSObject
{
NSMutableArray *commandQueue;
BOOL chanelFree;
}
- (void)send:(NSDictionary *)dictionary;
#end
And then send implementation:
- (void)send:(NSDictionary *)json
{
if ( YES == chanelFree ) {
// send command immediately
} else {
[commandQueue addObject:json];
}
}
If we want to test send implementation without exposing commandQueue(hence without braking encapsulation) we could get use of KVO:
-(void)testSend
{
ServerCommunicationManager* aTestObj = [ServerCommunicationManager new];
//prepare conditions
[aTestObj setValue:#NO forKey:#"channelFree"];
NSDictionary* dummyReq = #{};
[aTestObj send:dummyReq];
//check commandQueue state
XCTAssertEqualObjects(dummyReq, [[aTestObj valueForKey:#"commandQueue"] firstObject]);
XCTAssertTrue(1 == [[aTestObj valueForKey:#"commandQueue"] count]);
//more tests
}
KVC allows you to do KVO: That is, if you are observing a variable, you will only be notified of its changes if and only if the changes take place using KVC. If you modify a variable directly using its setter you are not going to be notified of its changes

objective-c/ios track screen usage

Let's say, for instance, that I want to place some code in the viewDidAppear: method for all UIViewController (including subclasses) objects from my project:
-(void)viewDidAppear:(BOOL)animated{
[super viewDidAppear:animated];
NSLog(#"Did show: %#:%#", NSStringFromClass([self class]), self.title);
}
Is there a way to do this without using categories (for UIViewController), and without having to manually change the superclass of all my view controllers to a new class that defines this method?
The reason I don't want to use a category is because I might want to define methods and call their super implementation.
For instance, is it possible to automatically add an intermediary class between UIViewController and whatever other classes inherit from UIViewController at runtime (or using preprocessor macros)?
The common way to achieve this is called method swizzling. Mike Ash has an article of how to do this correctly.
The general idea is to exchange the original implementation of an Objective-C method. Usually you call through to the original implementation from the inserted function/method.
Here's a quote from Mike's article:
The Obligatory Warning
Overriding methods on classes you don't own is a dangerous business. Your override could cause problems by breaking the assumptions of the class in question. Avoid it if it's at all possible. If you must do it, code your override with extreme care.

Why use "self" and what does it mean? [duplicate]

This question already has answers here:
What is self in ObjC? When should i use it?
(6 answers)
Closed 9 years ago.
So, I just started learning Objective-C and I've come across this "self" thing. I've only ever used C, but I think it's used in java too maybe? Can someone explain? Here's an example:
- (IBAction)digitPressed:(UIButton *)sender
{
NSString *digit = [sender currentTitle];
UILabel *myDisplay = [self display]; //why this?
}
Why isn't it just this?
- (IBAction)digitPressed:(UIButton *)sender
{
NSString *digit = [sender currentTitle];
UILabel *myDisplay = display; //why not like this?
}
display is a UILabel *
[self display], or self.display, refers to a property / method (property is just a shortcut for get/set method anyway) if you have something like this in the .h file
#property (weak, nonatomic) UILabel* display;
or
-(UILabel*)display;
Just display, or self->display refers to an instance variable. This is valid when you have declared an instance var like this:
#implementation MyClass {
UILabel* display;
}
If you have declared the property display in the .h file and haven't changed its default, the corresponding instance var will be _display (note the underscore), in which case the following will be the same:
self.display and self->_display
In this case it's an objective C messaging thing. When you see the brackets it's doing this:
[Object Message]
Basically self is the object and display is the message your sending it. Sending it a message is like a method call in another language, but a little different under the hood. So something like this:
[self doSomethingCool];
in objective C would translate to something like this in another language:
this.doSomethingCool();
of course if running a method on another object you'll replace self with that object like:
[myObject doSomethingCool];
in a lot of languages you don't really need to have the "this" in front of your method call, it's implied that if you don't include it you're running the method in the object you're working with. I got burned pretty early on when I started with something similar. I had a call to a datalayer method where you could save an object and it would give you an integer back. When I was saving the object I didn't put the self in front of the method call and it was essentially generating a new object and saving it and I wasn't getting the right integer back.
Using "self" just explicitly tells it "I'm using THIS object". Same thing with properties, I always use "self.MyProperty" instead of "MyProperty" because I want to be explicit and make sure I'm using the MyProperty of the object I'm working in. It's semi rare for a defect like that to hit you, where you expect to be using a certain object and the environment thinks you're using another, but man when you run into one it's a head scratcher because everything looks right.
The word self refers to the current object, which is your view controller instance in this case, and combining it with a method name, which is display, means you are sending the message display to self which is the view controller. This will invoke the method display declared in your view controller instance.
You might declare the display method in your view controller, for example:
- (UILabel)display
{
//your display method implementation returning UILabel instance
}
For the second one, it means you are referring to display variable. For example:
UILabel *display = [[UILabel alloc] init];
display is not a UILabel * - it might be a property with that type, or a method which returns a value of that type, but these a rather different things.
You need to go an read something about object oriented programming. The self in Objective-C is the current object reference, other OO languages call it this - both Java and C++ use that name. Understanding objects and methods is fundamental to using any of these languages.
There's a very good explanation of this here:
http://useyourloaf.com/blog/2011/02/08/understanding-your-objective-c-self.html
The key section for your question is the section on Objective-C 2.0 dot syntax:
Objective-C Dot Syntax
The dot syntax was introduced with Objective-C 2.0 and generates a lot
of debate. A number of experienced and long time Cocoa programmers
recommend avoiding it completely. Others such as Chris Hanson have a
different view about when to use properties and dot notation.
Whichever side of the argument you fall I guess the main thing is to
be consistent.
Anyway the main thing to understand about the dot syntax is that the
following two statements are doing the same thing:
self.timestamp = [NSDate date];
[self setTimestamp:[NSDate date]];
The dot is just a shortcut for the more traditional Objective-C method
call. Any time you see a dot you can replace it with the equivalent
square bracket method call syntax. It is important to understand
however that this is not the same as writing the following:
timestamp = [NSDate date]; Without the self object and the dot we are
no longer sending an object a message but directly accessing the ivar
named timestamp. Since this bypasses the setter method we will
overwrite the timestamp ivar without first releasing the old NSDate
object. We will also not retain the new object that we are assigning.
Both of these situations are bad!
Keep in mind that the examples were written without using ARC, so there's a lot of references to memory management, retain, release etc. It is however useful to see these examples so that you have some idea of what ARC is doing in the background.
In your example, you are not referring to the actual display property with [self display] you are in fact referring to an instance method of the "self" object which in this case is your UIViewController.

setDelegate explanation

Hi i am new to iphone developement, can any one explain me why setDelegate is used, where we should use it.
[request setDelegate:sender];
thanks in advance.
Delegates are simply a design pattern; there is no special syntax or language support.
A delegate is just an object that another object sends messages to when certain things happen, so that the delegate can handle application-specific details the original object wasn't designed for. It's a way of customizing behavior without subclassing.
Some classes, for example NSSpeechSynthesizer, include delegate support. Unlike a protocol, failure to provide a delegate method does not provoke an error: the class always provides a method, but calls yours instead, if it exists.
For example, NSSpeechSynthesizer has a method
-(void) speechSynthesizer:(NSSpeechSynthesizer*)sender
didFinishSpeaking:(BOOL)complete;
If you provide an identically declared method, in class Fred, it will be called instead of the synthesiser's own method, provided you have earlier done, in that class,
speech = [[NSSpeechSynthesizer alloc] initWithVoice:#"com.apple.speech.synthesis.voice.Albert"];
[speech setDelegate:self];
This will work, though the compiler will warn if you did not announce yourself as a delegate by
#interface Fred : NSObject <NSSpeechSynthesizerDelegate>, in that
{
. . .
(This example is adapted from Cocoa Programming... by Hillegass).

Resources