What is cocoa?
Cocoa is an application environment for both the Mac OS X operating system and iOS, the
operating system used on Multi-Touch devices such as iPhone, iPad, and iPod touch. It
consists of a suite of object-oriented software libraries, a runtime system, and an integrated
development environment.
Cocoa is a set of object-oriented frameworks that provides a runtime environment for
applications running in Mac OS X and iOS. Cocoa is the preeminent application environment
for Mac OS X and the only application environment for iOS. (Carbon is an alternative
environment in Mac OS X, but it is a compatibility framework with procedural programmatic
interfaces intended to support existing Mac OS X code bases.) Most of the applications you
see in Mac OS X and iOS, including Mail and Safari, are Cocoa applications.
Development tools in cocoa?
Xcode and Interface Builder.
Latest versions of Xcode and iOS?
Xcode-4.5, iOS 6
Does multiple Inheritance supports in objective-c?
Yes it supports, We can achieve it using Protocols concept.
What is a protocol?
Protocols declare methods that can be implemented categorieby any class. Protocols are useful in at
least three situations:
Fortune Info Solutions – iOS(iPhone) Interview Questions
- To declare methods that others are expected to implement
- To declare the interface to an object while concealing its class
- To capture similarities among classes that are not hierarchically related
A protocol is simply a list of method declarations, unattached to a class definition. For
example, these methods that report user actions on the mouse could be gathered into a
protocol:
- (void)mouseDown:(NSEvent *)theEvent;
- (void)mouseDragged:(NSEvent *)theEvent;
- (void)mouseUp:(NSEvent *)theEvent;
Any class that wanted to respond to mouse events could adopt the protocol and implement its
methods. to get mouse events one should subclass from NSResponder and NSWindow
The syntax for declaring a protocol is simple:
@protocol NSCopying
- (id)copyWithZone:(NSZone *)zone;
@end
A class that adopts theWhat is an Abstract class?NSCopying protocol might be declared like this:
@interface CopyMachine : NSObject <NSCopying, NSCoding>The compiler sees that the CopyMachine class conforms to the NSCopying and NSCoding protocols, and it will issue a warning if the required methods in those classes are not implemented. Note also that protocol conformity is inherited—subclasses of CopyMachine, for example, will also conform to those protocols, and can re-implement (override) those methods as necessary.
An abstract class, (sometimes called an abstract base class), is a class that cannot be instantiated. Some classes are designed only or primarily so that other classes can inherit from them.
These abstract classes group methods and instance variables that can be used by a number of
subclasses into a common definition.
The abstract class is typically incomplete by itself, but contains useful code that reduces the
implementation burden of its subclasses. (Because abstract classes must have subclasses to be
useful, they’re sometimes also called abstract superclasses.)
// MyObject.h
#import
@protocol IMyObject
-(void) myMethod;
@end
@interface MyObject : NSObject {
NSUInteger myID;
}
@property (nonatomic) NSUInteger myID;
-(void) myMethod2;
@end
// MyObject
#import "MyObject.h"
@implementation MyObject
@synthesize myID;
- (id)init
{
[self doesNotRecognizeSelector:_cmd];
[self release];
return nil;
}
-(void) myMethod {
[self doesNotRecognizeSelector:_cmd];
}
-(void) myMethod2 {
//do stuff
}
-(void) myMethod2 {
//do stuff
}
@end
A category allows you to add methods to an existing class—even to one for which you do not
have the source.
Categories are a powerful feature that allows you to extend the functionality of existing
classes without subclassing.
Using categories, you can also distribute the implementation of your own classes among
several files.
Difference between a protocol and Category?
A Protocol say's "Here are some methods I would like you to implement".
A Category say's "I am extending the functionality of this class with these additional
methods"
Difference between protocol in objective c and interfaces in java?
Protocol is also way to relate classes that are not related in inheritance hierarchy. Protocols and interfaces both are used to achieve multiple inheritance.
There is minor difference between these two. In Objective-C, protocols also implement NSObject protocol to access all the mehthods in NSObject
@protocol WebProtocol <NSObject>
@end
If I don’t implement NSObject explicitly, I will not be able to access NSObject methods like retain, release etc. when I access through WebProtocol instance.
While in Java you don’t need to implement Object interface explicitly. It is implicitly implemented.
Explain Singleton classes?
It's an extremely powerful way to share data between different parts of code without having
to pass the data around manually.
Fortune Info Solutions – iOS(iPhone) Interview Questions
When do we use @property and @synthesize?
1 down vote accepted
@property : you use it when you want to:
You can use some of the really useful generated code like nonatomic, atomic, retain without
writing any lines of code.
You also have getter and setter methods. To use this, you have 2 other ways: @synthesize or
@dynamic:
@synthesize, compiler will generate the getter and setter automatically for you,
@dynamic: you have to write them yourself.
@property is really good for memory management, for example: retain.
How can you do retain without @property?
if (_variable != object) {
[_variable release];
_variable = nil;
_variable = [object retain];
}
How can you use it with @property?
self.variable = object;
When you are calling the above line, you actually call the setter like [self setVariable:object]
and then the generated setter will do its job
assign, retain, copy?
assign: "Specifies that the setter uses simple assignment.This is the default.You typically use
this attribute for scalar type", So you can imagine assigning a float(which isn't an object), So
can't be retained, copied..etc.
retain: "Specifies that retain should be involved on the object upon assignment... The
previous value is sent a release message". So you can imagine an NSString instance(Which is
an object and which you probably want to retain).
Copy: "Specifies the copy of object should be assigned and the previous values is sent a
release message.
Different types of data storages in iOS?
SQLite3, Property lists, Core data, files, NSUserDefaults for small data
Different types of webservices?
1.NSXMLParser - Synchronous(Apple's default webservice provider)
2.LibXmlParser - Asynchronous
3.JSON - Its a light weight webservice provider and very easy to use.
And there are many more webservices like Touch XML, KissXML... etc.
Fortune Info Solutions – iOS(iPhone) Interview Questions
iOS Architecture?
iOS Architecture mainly divided into 4 layers.
1.Cocoa Touch Layer
2.Media Layer
3.Core Services Layer
4.Core OS Layer
The API' Under Cocoa Touch Layer as follows:
-AddressBookUI
-EventKitUI
-GameKit
-iAd
-MapKit
-MessageUI
-UIKit
The API' Media Layer as follows:
-AssetsLibrary
-AudioToolbox
-AudioUnit
-AvFoundation
-CoreAudio
-CoreGraphics
-CoreImage
-CoreMIDI
-CoreText
-CoreVideo
-GLKit
-ImageIO
-MediaPlayer
-OpenAL
-OpenGLES
-QuartzCore
The API' Under Core Services Layer as follows:
-Accounts
-AddressBook
-CFNetwork
-CoreData
-CoreFoundation
-CoreLocation
-CoreMedia
-CoreMotion
-CoreTelephony
-EventKit
-Foundation
-MobileCoreServices
-NewsstandKit
Fortune Info Solutions – iOS(iPhone) Interview Questions
-QuickLook
-StoreKit
-SystemConfiguration
-UIAutomation
The API' Under Core OS Layer as follows:
-Accelerate
-CoreBluetooth
-ExternalAccesory
-Security
-System
Debugging technics in iOS?
GDB, Breakpoints, NSZombie, Instruments.
Features in iOS 5?
iCloud Storage:
iCloud Storage APIs enable your apps to store user documents and key value data and
wirelessly push any changes to all your user's computers and devices at the same time —
automatically.
Notification Center:
Notification Center provides an innovative way to easily display and manage your app
notifications without interrupting your users. Notification Center in iOS 5 builds on the
existing notification system, so your existing local and push notifications just work.
Provisioning of push notifications is now built right into Xcode making it even easier to
implement.
Newsstand:
Publish the latest issues of your magazines and newspapers directly to Newsstand, the new
folder on the Home Screen. Newsstand Kit provides everything you need to update new
issues in the background, so you can always present the most recent cover art. Apps built for
Newsstand use In-App Purchase subscriptions, making it easy for users to manage their autorenewable
subscriptions. And it's now possible to provision your app for In-App Purchase
within Xcode
Automatic Reference Counting:
Automatic Reference Counting (ARC) for Objective-C makes memory management the job
of the compiler. By enabling ARC with the new Apple LLVM compiler, you will never need
to type retain or release again, dramatically simplifying the development process, while
reducing crashes and memory leaks. The compiler has a complete understanding of your
objects, and releases each object the instant it is no longer used, so apps run as fast as ever,
with predictable, smooth performance.
Twitter Integration:
Tweet directly from your apps using the new Tweet sheet. It provides all of the features
available to built-in apps, including URL shortening, attaching current location, character
count and hosting photos on Twitter. And if your app is a Twitter client, it's easy to tie into
the single sign-on service using the Twitter APIs. It's even possible to migrate existing
accounts to iOS.
Fortune Info Solutions – iOS(iPhone) Interview Questions
Storyboards:
Layout the workflow of your app using the new Storyboards feature built into the design
tools of Xcode. Created for apps that use navigation and tab bars to transition between views,
Storyboards eases the development by managing the view controllers for you. You can
specify the transitions and segues that are used when switching between views without
having to code them by hand.
AirPlay:
Introduced in iOS 4.2, AirPlay streams video, audio and photos to Apple TV. With iOS 5, it's
now possible to wirelessly mirror everything on your iPad 2 to an HDTV via Apple TV. Your
apps are mirrored automatically. With additional APIs your app can display different content
on each of the HDTV and the iPad 2 screens. In iOS 5, apps built with AV Foundation can
now stream video and audio content through AirPlay, and AirPlay now supports encrypted
streams delivered via HTTP Live Streaming
Core Image:
Create amazing effects in your camera and image editing apps with Core Image. Core Image
is a hardware-accelerated framework that provides an easy way to enhance photos and
videos. Core Image provides several built-in filters, such as color effects, distortions and
transitions. It also includes advanced features such as auto enhance, red-eye reduction and
facial recognition.
Game Center:
Game Center is taking multiplayer gaming on iOS one step further with the addition of turnbased
game support. With turn-based games, players can play when they want and Game
Center will manage each turn for them. Game Center will automatically send the next player
a push notification via Notification Center and manage multiple game sessions. Other
developer additions to Game Center include, adding players to existing multiplayer games,
displaying achievement notification banners, and support for distinct icons for each
leaderboard.
OpenGL ES:
It's now even easier to develop great looking games that take advantage of the latest iOS
hardware. GLKit is a new high-level framework that combines the best practices of advanced
rendering and texture techniques with the latest OpenGL ES 2.0 features. It's optimized to
take advantage of hardware accelerated math operations, so you get the best performance
without all the work. iOS 5 SDK also includes new Apple-developed OpenGL ES extensions
designed specifically for advanced game developers. And the new OpenGL ES debugger in
Xcode allows you to track down issues specific to OpenGL ES in your code.
iMessage:
iMessage is a new messaging service that works between all iOS 5 users over Wi-Fi and 3G.
iMessages are automatically pushed to all iOS 5 devices, making it easy to maintain one
conversation across iPhone, iPad and iPod touch. In iOS 5 SDK, the Message sheet now
supports the iMessage service, so you can start individual or group text conversations from
within your app.
Fortune Info Solutions – iOS(iPhone) Interview Questions
New Instruments:
In addition to ARC, iOS 5 SDK includes several new instruments including time profiler with
CPU strategy which gives you a new way to view time profiler data, as well as system trace,
network activity and network connections instruments.
PC Free:
iOS 5 includes a host of features that give users the power, freedom, and flexibility to use
their iOS devices without a Mac or PC. Expand the functionality of your apps and remove the
need for users to access a PC. Take advantage of iCloud Storage to store documents and user
data, so they are updated automatically and users can access them from all of their devices.
Location simulation:
Now you can test your location-based features in your app without leaving your desk. You
can now select from preset locations and routes within the iOS Simulator and pick a custom
latitude and longitude with accuracy while you're running your simulated app.
Difference between shallow copy and deep copy?
Shallow copy is also known as address copy. In this process you only copy address not actual data while in deep copy you copy data.
Suppose there are two objects A and B. A is pointing to a different array while B is pointing to different array. Now what I will do is following to do shallow copy. Char *A = {‘a’,’b’,’c’}; Char *B = {‘x’,’y’,’z’}; B = A; Now B is pointing is at same location where A pointer is pointing.Both A and B in this case sharing same data. if change is made both will get altered value of data.Advantage is that coping process is very fast and is independent of size of array. while in deep copy data is also copied. This process is slow but Both A and B have their own copies and changes made to any copy, other will copy will not be affected.
What is advantage of categories? What is difference between implementing a category and inheritance?
You can add method to existing class even to that class whose source is not available to you. You can extend functionality of a class without sub-classing. You can split implementation in multiple classes. While in Inheritance you subclass from parent class and extend its functionality.
Difference between categories and extensions?
Class extensions are similar to categories. The main difference is that with an extension, the compiler will expect you to implement the methods within your main @implementation, whereas with a category you have a separate @implementation block. So you should pretty much only use an extension at the top of your main .m file (the only place you should care about ivars, incidentally) — it’s meant to be just that, an extension.
A Category is a feature of the Objective-C language that enables you to add methods (interface and implementation) to a class without having to make a subclass. There is no runtime difference—within the scope of your program—between the original methods of the class and the methods added by the category. The methods in the category become part of the class type and are inherited by all the class’s subclasses.As with delegation, categories are not a strict adaptation of the Decorator pattern, fulfilling the intent but taking a different path to implementing that intent. The behavior added by categories is a compile-time artifact, and is not something dynamically acquired. Moreover, categories do not encapsulate an instance of the class being extended.
The Cocoa frameworks define numerous categories, most of them informal protocols . Often they use categories to group related methods. You may implement categories in your code to extend classes without subclassing or to group related methods. However, you should be aware of these caveats:
You cannot add instance variables to the class.
If you override existing methods of the class, your application may behave unpredictably.
Refer: Categories and Extensions
//NSStringExtensions.h
@interface NSString (reverse)
-(NSString *) reverseString;
@end
//NSStringExtensions.h
@interface NSString (reverse)
-(NSString *) reverseString;
@end
//NSStringExtensions.m
@implementation NSString (reverse)
-(NSString *)reverseString {
int length = [self length];
NSMutableString *reversedString;
reversedString = [[NSMutableString alloc] initWithCapacity: length];
while (length > 0) {
[reversedString appendString:[NSString stringWithFormat:@"%C", [self characterAtIndex:--length]]];
}
return [reversedString autorelease];
}
@end //how to call from main ;
we still need to include our header file into the main project.
NSString *test = @"this is me";
[test reverseString];
@implementation NSString (reverse)
-(NSString *)reverseString {
int length = [self length];
NSMutableString *reversedString;
reversedString = [[NSMutableString alloc] initWithCapacity: length];
while (length > 0) {
[reversedString appendString:[NSString stringWithFormat:@"%C", [self characterAtIndex:--length]]];
}
return [reversedString autorelease];
}
@end //how to call from main ;
we still need to include our header file into the main project.
NSString *test = @"this is me";
[test reverseString];
//////////////////////////
other e.g.
//////////////////////////
#import <Foundation/Foundation.h>
#import "Numz.h"
// Categories
@interface Numz (moreMethod)
- (void) sub: (int) a: (int) b;
- (void) mul: (int) a: (int) b;
@end
@implementation Numz (moreMethod)
- (void) sub: (int) a: (int) b
{
NSLog(@"These numbers subtracted are %i", a - b);
}
- (void) mul: (int) a: (int) b
{
NSLog(@"These numbers multiplied are %i", a * b);
}
@end
int main(int argc, const char *argv[])
{
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
Numz *n = [[Numz alloc] init];
[n sub: 100: 50];
[n mul: 100: 40];
[n release];
[pool drain];
return 0;
}
other e.g.
//////////////////////////
#import <Foundation/Foundation.h>
#import "Numz.h"
// Categories
@interface Numz (moreMethod)
- (void) sub: (int) a: (int) b;
- (void) mul: (int) a: (int) b;
@end
@implementation Numz (moreMethod)
- (void) sub: (int) a: (int) b
{
NSLog(@"These numbers subtracted are %i", a - b);
}
- (void) mul: (int) a: (int) b
{
NSLog(@"These numbers multiplied are %i", a * b);
}
@end
int main(int argc, const char *argv[])
{
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
Numz *n = [[Numz alloc] init];
[n sub: 100: 50];
[n mul: 100: 40];
[n release];
[pool drain];
return 0;
}
Use Class Extensions to Hide Private Information
“class
extension”, @interface SVProgressHUD (), that has several property
declarations. If you’re unfamiliar with class extensions, they are like
categories except they have special powers. The declaration of a class
extension looks like that of a category but it has no name between the
() parentheses. Class extensions can have properties and instance
variables, something that categories can’t, but you can only use them
inside your .m file. (In other words, you can’t use a class extension on
someone else’s class.)
The cool thing about class extensions is that they allow you to add private properties and method names to your classes. If you don’t want to expose certain properties or methods in your public @interface, then you can put them in a class extension. That’s exactly what the author of SVProgressHUD did.
Objective-C 2.0 has a mechanism allowing to add private methods and private variables to a class (the encapsulation in Objective-C is on the highest level). The name of the feature is Class Extensions.
Class Extensions is a great place to redeclare a property publicly declared as read only - in the extension the property can be redeclared with the read-write attribute.
The cool thing about class extensions is that they allow you to add private properties and method names to your classes. If you don’t want to expose certain properties or methods in your public @interface, then you can put them in a class extension. That’s exactly what the author of SVProgressHUD did.
Objective-C 2.0 has a mechanism allowing to add private methods and private variables to a class (the encapsulation in Objective-C is on the highest level). The name of the feature is Class Extensions.
Class Extensions is a great place to redeclare a property publicly declared as read only - in the extension the property can be redeclared with the read-write attribute.
The primary interface for a class is used to define the way that other classes are expected to interact with it. In other words, it’s the public interface to the class.
Class extensions are often used to extend the public interface with additional private methods or properties for use within the implementation of the class itself. It’s common, for example, to define a property as
readonly
in the interface, but as readwrite
in a class extension declared above the implementation, in order that the internal methods of the class can change the property value directly.
As an example, the
XYZPerson
class might add a property called uniqueIdentifier
, designed to keep track of information like a Social Security Number in the US.
so the
XYZPerson
class interface might declare this property as readonly
, and provide some method that requests an identifier be assigned, like this:@interface XYZPerson : NSObject
|
...
|
@property (readonly) NSString *uniqueIdentifier;
|
- (void)assignUniqueIdentifier;
|
@end
|
This means that it’s not possible for the
uniqueIdentifier
to be set directly by another object. If a person doesn’t already have one, a request must be made to assign an identifier by calling the assignUniqueIdentifier
method.
In order for the
XYZPerson
class to be able to change the property internally, it makes sense to redeclare the property in a class extension that’s defined at the top of the implementation file for the class:@interface XYZPerson ()
|
@property (readwrite) NSString *uniqueIdentifier;
|
@end
|
|
@implementation XYZPerson
|
...
|
@end
|
This means that the compiler will now also synthesize a setter method, so any method inside the
XYZPerson
implementation will be able to set the property directly using either the setter or dot syntax.
By declaring the class extension inside the source code file for the
XYZPerson
implementation, the information stays private to the XYZPerson
class. If another type of object tries to set the property, the compiler will generate an error.What are KVO and KVC?
Key-Value Coding: Key-Value Coding (KVC) is a Cocoa protocol for getting and setting values generically. The idea behind key-value coding is pretty simple: instead of directly getting and setting specific properties on an object, key-value coding involves passing in a "key" (usually a string) and getting or setting the property associated with that key. The key-value coding approach is better because it doesn't have to handle the edit of each property as a separate condition. This is the essence of key-value coding. Key-value coding remains just as efficient as the data set increases in size. A table with 1,000 columns would require the same amount of code to edit.
Without key-value coding, the
NSTableViewDataSource
method to handle an edit for one of the rows might look like this:- ( void )tableView:( NSTableView *)aTableView setObjectValue :( NSString *)anObject forTableColumn :( NSTableColumn *)aTableColumn row :( int )rowIndex { if ([[aTableColumn identifier ] isEqual : @"name" ]) { [[records objectAtIndex :rowIndex] setName :anObject]; } else if ([[aTableColumn identifier ] isEqual : @"address" ]) { [[records objectAtIndex :rowIndex] setAddress :anObject]; } } |
- ( void )tableView:( NSTableView *)aTableView setObjectValue :( NSString *)anObject forTableColumn :( NSTableColumn *)aTableColumn row :( int )rowIndex { [[records objectAtIndex :rowIndex] setValue :anObject forKey :[aTableColumn identifier ]]; } |
Normally instance variables are accessed through properties or accessors but KVC gives another way to access variables in form of strings. In this way your class acts like a dictionary and your property name for example “age” becomes key and value that property holds becomes value for that key. For example, you have employee class with name property.
You access property like
NSString age = emp.age;
setting property value.
emp.age = @”20″;
Now how KVC works is like this
[emp valueForKey:@"age"];
[emp setValue:@"25" forKey:@"age"];
Key Paths: You can combine KVC and dot syntax to create a key path. Imagine that we have a store class; we can use the following syntax
[store setValue:[NSNumber numberWithFloat:2.99] forKeyPath:@“gallonOfMilk.price];
Using key-value coding is not mandatory — it is certainly possible to implement whole projects without it. However, it is one of the best code patterns for reducing repetitious code and making classes more reusable by decoupling actions from properties and data
KVO : The mechanism through which objects are notified when there is change in any of property is called KVO.
For example, person object is interested in getting notification when accountBalance property is changed in BankAccount object.To achieve this, Person Object must register as an observer of the BankAccount’s accountBalance property by sending an addObserver:forKeyPath:options:context: message.
KVC and KVO are not really used in simple applications. However, with multiple controllers that need to interact with each other, KVC and KVO can be used to great benefit. KVO, which stands for Key-Value Observing, registers a class for notifications when a key-value is changed in any other class. It is an effective way to allow multiple controllers to communicate without resorting to a tangle of protocols.
Can we use two tableview controllers on one view controller?
Yes, we can use two tableviews on the same view controllers and you can differentiate between two by assigning them tags…or you can also check them by comparing their memory addresses.
What is keyword atomic in Objective C?
When you place keyword atomic with a property, it means at one time only one thread can access it.
Used for multi-threading. e.g.when two processes are trying to change the state of a single property then a lock is placed on the property until the process completes and then it is unlocked for the other process to access it.
In obj C - property's are atomic by default.
What are mutable and immutable types in Objective C?
Mutable means you can change its contents later but when you mark any object immutable, it means once they are initialized, their values cannot be changed. For example, NSArray, NSString values cannot be changed after initialized.
When we call objective c is runtime language what does it mean?
Objective-C runtime is runtime library that is open source that you can download and understand how it works. This library is written in C and adds object-oriented capabilities to C and makes it objective-c. It is only because of objective c runtime that it is legal to send messages to objects to which they don’t know how to respond to. Methods are not bound to implementation until runtime. Objective-C defers its decisions from compile time to run time as much as it can. For example, at runtime, it can decide to which object it will send message or function.
What is difference between NSNotification and delegate?
Delegate is passing message from one object to other object. It is like one to one communication while nsnotification is like passing message to multiple objects at the same time. All other objects that have subscribed to that notification or acting observers to that notification can or can’t respond to that event. Notifications are easier but you can get into trouble by using those like bad architecture. Delegates are more frequently used and are used with help of protocols.
Swap the two variable values without taking third variable?
int x=10; int y=5; x=x+y; NSLog(@”x==> %d”,x);
y=x-y; NSLog(@”Y Value==> %d”,y);
x=x-y; NSLog(@”x Value==> %d”,x);
Thanks to Subrat for answering this question.
What is push notification?
Imagine, you are looking for a job. You go to software company daily and ask sir “is there any job for me” and they keep on saying no. Your time and money is wasted on each trip.(Pull Request mechanism)
So, one day owner says, if there is any suitable job for you, I will let you know. In this mechanism, your time and money is not wasted. (Push Mechanism)
How it works?
This service is provided by Apple in which rather than pinging server after specific interval for data which is also called pull mechanism, server will send notification to your device that there is new piece of information for you. Request is initiated by server not the device or client.
Flow of push notification
Your web server sends message (device token + payload) to Apple push notification service (APNS) , then APNS routes this message to device whose device token specified in notification.
What is polymorphism?
This is very famous question and every interviewer asks this. Few people say polymorphism means multiple forms and they start giving example of draw function which is right to some extent but interviewer is looking for more detailed answer.
Ability of base class pointer to call function from derived class at runtime is called polymorphism.
For example, there is super class human and there are two subclasses software engineer and hardware engineer. Now super class human can hold reference to any of subclass because software engineer is kind of human. Suppose there is speak function in super class and every subclass has also speak function. So at runtime, super class reference is pointing to whatever subclass, speak function will be called of that class. I hope I am able to make you understand.
What is responder chain?
Suppose you have a hierarchy of views such like there is superview A which have subview B and B has a subview C. Now you touch on inner most view C. The system will send touch event to subview C for handling this event. If C View does not want to handle this event, this event will be passed to its superview B (next responder). If B also does not want to handle this touch event it will pass on to superview A. All the view which can respond to touch events are called responder chain. A view can also pass its events to uiviewcontroller. If view controller also does not want to respond to touch event, it is passed to application object which discards this event.
15. Can we use two tableview controllers on one view controller?
Yes. We can use as many table views in one view controllers. To differentiate between tableviews, we can assign table views different tags.
16. Can we use one tableview with two different datasources? How you will achieve this?
Yes. We can conditionally bind tableviews with two different data sources.
iOS
Questions for Beginners
Whats
fast enumeration?
Fast
enumeration is a language feature that allows you to enumerate over
the contents of a collection. (Your code will also run faster because
the internal implementation reduces message
send overhead and increases pipelining potential.)
Whats a struct?
A
struct is a special C data type that encapsulates other pieces of
data into a single cohesive unit. Like an object, but built into C. *
Whats the difference between NSArray and NSMutableArray?
NSArrayʼs
contents can not be modified once itʼs been created whereas a
NSMutableArray can be modified as needed, i.e items can be
added/removed from it.
When to use NSMutableArray and when to use NSArray?
Normally we use mutable version of array where data in the array will change. For example, you are passing a array to function and that function will add some elements to that array or will remove some elements from array, then you will select NSMutableArray.
When you don’t want to change you data, then you store it into NSArray. For example, the country names you will put into NSArray so that no one can accidentally modify it.
When to use NSMutableArray and when to use NSArray?
Normally we use mutable version of array where data in the array will change. For example, you are passing a array to function and that function will add some elements to that array or will remove some elements from array, then you will select NSMutableArray.
When you don’t want to change you data, then you store it into NSArray. For example, the country names you will put into NSArray so that no one can accidentally modify it.
Explain retain counts.
Retain
counts are the way in which memory is managed in Objective-C. When
you create an object, it has a retain count of 1. When you send an
object a retain message, its retain count is incremented by 1. When
you send an object a release message, its retain count is decremented
by 1. When you send an object a autorelease message, its retain count
is decremented by 1 at some stage in the future. If an objectʼs
retain count is reduced to 0, it is deallocated.
Can you explain what happens when you call autorelease on an object?
When
you send an object a autorelease message, its retain count is
decremented by 1 at some stage in the future. The object is added to
an autorelease pool on the current thread. The main thread loop
creates an autorelease pool at the beginning of the function, and
release it at the end. This establishes a pool for the lifetime of
the task. However, this also means that any autoreleased objects
created during the lifetime of the task are not disposed of until the
task completes. This may lead to the taskʼs memory footprint
increasing unnecessarily. You can also consider creating pools with a
narrower scope or use NSOperationQueue with itʼs own autorelease
pool. (Also important – You only release or autorelease objects you
own.)
Whats the difference between frame and bounds?
The
frame of a view is the rectangle, expressed as a location (x,y) and
size (width,height) relative to the superview it is contained within.
The bounds of a view is the rectangle, expressed as a location (x,y)
and size (width,height) relative to its own coordinate system (0,0).
Is a delegate retained?
No,
the delegate is never retained! Ever! Only one exception is delegate for CAAnimation, which is retained.
Outline the class hierarchy for a UIButton until NSObject.
UIButton
inherits from UIControl, UIControl inherits from UIView, UIView
inherits from UIResponder, UIResponder inherits from the root class
NSObject
What is dynamic?
You
use the @dynamic keyword
to tell the compiler that you will fulfill the API contract implied
by a property either by providing method implementations directly or
at runtime using other mechanisms such as dynamic loading of code or
dynamic method resolution. It suppresses the warnings that the
compiler would otherwise generate if it can’t find suitable
implementations. You should use it only if you know that the methods
will be available at runtime.
@dynamic creates the accessor methods at runtime, while @synthesize will create the accessors at build time.
@dynamic creates the accessor methods at runtime, while @synthesize will create the accessors at build time.
The
Typically, you would use
You are correct that in most normal cases you would not use
@dynamic
keyword tells the
compiler that you will provide accessor methods dynamically at runtime.
This can be done using the Objective-C runtime functions. Typically, you would use
@dynamic
with things like Core Data, where Core Data will provide the accessors based on the Core Data model.You are correct that in most normal cases you would not use
@dynamic
. Typically, you would just use @property
or @property
and @synthesize
.
Some accessors are created dynamically at runtime, such as certain ones used in CoreData's NSManagedObject class. If you want to declare and use properties for these cases, but want to avoid warnings about methods missing at compile time, you can use the @dynamic directive instead of @synthesize.
Using the @dynamic directive essentially tells the compiler "don't worry about it, a method is on the way."
@synthesize will generate getter and setter methods for your property. @dynamic just tells the compiler that the getter and setter methods are implemented not by the class itself but somewhere else (like the superclass)
Uses for @dynamic are e.g. with subclasses of
NSManagedObject
(CoreData) or when you want to create an outlet for a property defined by a superclass that was not defined as an outlet:
Super class:
@property (nonatomic, retain) NSButton *someButton;
...
@synthesize someButton;
Subclass:
@property (nonatomic, retain) IBOutlet NSButton *someButton;
...
@dynamic someButton;
Easy NSString substring?
Sadly, creating a simple substring in Objective-C isn't quite as obvious as in other languages. Here's a basic method to grab a substring of a given string before a defined character, in my case the ":" character:
If you wanted grab a string between two characters, you could do:
NSRange end = [_contentsOfElement rangeOfString:@":"];
[myVar setName:[_contentsOfElement substringWithRange:NSMakeRange(0, end.location)]];
If you wanted grab a string between two characters, you could do:
NSRange start = [_contentsOfElement rangeOfString:@"|"];
NSRange end = [_contentsOfElement rangeOfString:@":"];
[myVar setName:[_contentsOfElement substringWithRange:NSMakeRange(start.location, end.location)]];
UITextView automatic keyboard display
- (void)viewDidLoad {
[super viewDidLoad];
[commentTxt becomeFirstResponder];
}
Hiding the keyboard when using UISearchBar and UITableView
@interface YourViewController : UIViewController <UITableViewDataSource, UITableViewDelegate, UIScrollViewDelegate>
- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView {
[search resignFirstResponder];
}
Declaring constants in Objective-C
In your header .h file you will need the following:
#import
extern NSString * const BaseURL;
@interface ClassName : NSObject {
You will then need to set it's value in your main .m file as follows:
#import "ClassName.h"
NSString * const BaseURL = @"http://some.url.com/path/";
@implementation ClassName
You can now access this constant throughout your class or subclasses. Here's an example of usage:
NSString *urlString = [NSString stringWithFormat:@"%@%@", BaseURL, @"filename.html"];
Declaring constants in Objective-C
In your header .h file you will need the following:
You will then need to set it's value in your main .m file as follows:
You can now access this constant throughout your class or subclasses. Here's an example of usage:
#import
extern NSString * const BaseURL;
@interface ClassName : NSObject {
You will then need to set it's value in your main .m file as follows:
#import "ClassName.h"
NSString * const BaseURL = @"http://some.url.com/path/";
@implementation ClassName
You can now access this constant throughout your class or subclasses. Here's an example of usage:
NSString *urlString = [NSString stringWithFormat:@"%@%@", BaseURL, @"filename.html"];
If
I call performSelector:withObject:afterDelay: – is the object
retained?
Yes,
the object is retained. It creates a timer that calls a selector on
the current threads run loop. It may not be 100% precise time-wise as
it attempts to dequeue the message from the
run loop and perform the selector.
Whats the NSCoder class used for?
NSCoder
is an abstractClass which
represents a stream of data. They are used in Archiving
and Unarchiving objects. NSCoder objects are usually used
in a method that is being implemented so that the class conforms to
the protocol. (which has something like encodeObject
and decodeObject methods in them).
Whats an NSOperationQueue and how/would you use it?
The
NSOperationQueue class regulates the
execution of a set of NSOperation
objects. An operation
queue is generally used to perform
some asynchronous operations
on a background
thread so as not
to block the main
thread.
Explain the correct way to manage Outlets memory
Create
them as properties in the header that are retained.
In the viewDidUnload set the outlets to nil(i.e
self.outlet = nil). Finally in dealloc make sure to release
the outlet.
iOS Questions for Expert level
Is the delegate for a CAAnimation retained?
Yes
it is!! This is one of the rare exceptions to memory management
rules.
What happens when the following code executes?
Ball
*ball = [[[[Ball alloc] init] autorelease] autorelease];
It
will crash because itʼs added twice to the autorelease
pool and when it it dequeued the autorelease pool calls release
more than once.
Explain the difference between NSOperationQueue concurrent and non-concurrent.
In
the context of an NSOperation object, which runs in an
NSOperationQueue, the terms concurrent and non-concurrent do not
necessarily refer to the side-by-side execution of threads. Instead,
a non-concurrent operation is one that executes using the environment
that is provided for it while a concurrent operation is responsible
for setting up its own execution environment.
Implement your own synthesized methods for the property NSString *title.
Well
you would want to implement the getter and setter for the title
object. Something like this: view source print?
-
(NSString*) title // Getter method
{
return
title;
}
-
(void) setTitle: (NSString*) newTitle
//Setter method
{
if
(newTitle != title)
{
[title
release];
title
= [newTitle retain]; // Or copy, depending on your needs.
}
}
Implement the following methods: retain, release, autorelease.
-(id)retain
{
NSIncrementExtraRefCount(self);
return
self;
}
-(void)release
{
if(NSDecrementExtraRefCountWasZero(self))
{
NSDeallocateObject(self);
}
}
-(id)autorelease
{
// Add the object to the autorelease pool
// Add the object to the autorelease pool
[NSAutoreleasePool
addObject:self];
return
self;
}
Explain the steps involved in submitting the App to App-Store.
- Test your application
- Create a Distribution Provisioning Profile
- status of your iTunes Connect app record should be “Waiting for Upload”
- download the distribution provisioning profile
- import the .mobileprovision extension file ( distrubition provisioning profile) to provisioning profile folder
- set code signing identity to distribution certificate
- Create and Validate the Archive
- submit yr archive to appstore
- they will review the application
you
have the option to manually uplaod or auto load
What are all the newly added frameworks iOS 4.3 to iOS 5.0?
• Accounts
• CoreBluetooth
• CoreImage
• GLKit
• GSS
• NewsstandKit
• Twitter
What are the App states. Explain them?
- Not running State: The app has not been launched or was running but was terminated by the system.
- Inactive state: The app is running in the foreground but is currently not receiving events. (It may be executing other code though.) An app usually stays in this state only briefly as it transitions to a different state. The only time it stays inactive for any period of time is when the user locks the screen or the system prompts the user to respond to some event, such as an incoming phone call or SMS message
- Active state: The app is running in the foreground and is receiving events. This is the normal mode for foreground apps
- Background state: The app is in the background and executing code. Most apps enter this state briefly on their way to being suspended. However, an app that requests extra execution time may remain in this state for a period of time. In addition, an app being launched directly into the background enters this state instead of the inactive state. For information about how to execute code while in the background, see “Background Execution and Multitasking.”
- Suspended state:The app is in the background but is not executing code. The system moves apps to this state automatically and does not notify them before doing so. While suspended, an app remains in memory but does not execute any code. When a low-memory condition occurs, the system may purge suspended apps without notice to make more space for the foreground app.
Explain the options and bars available in xcode 4.2/4.0 workspace
window ?
Multitasking support is available from which version?
iOS
4.0
How many bytes we can send to apple push notification server.
256 bytes.
What is Automatic Reference Counting (ARC) ?
ARC
is a compiler-level feature that simplifies the process of
managing the lifetimes of Objective-C objects. Instead of
you having to remember when to retain or release an object,
ARC evaluates the lifetime requirements of your objects
and automatically inserts the appropriate method calls at compile
time.
Can you just explain about memory management in iOS?
Refer: iOS
Memory Management
Memory
management
is the programming discipline of managing
the life cycles
of objects
and
freeing them when they are no longer needed.
Managing object memory is a matter of performance; if an application
doesn’t free unneeded objects, its memory footprint grows and
performance suffers. Memory
management in
a Cocoa application that doesn’t use garbage collection is based on
a reference
counting model.
When you create
or copy an object, its retain
count
is 1.
Thereafter other objects
may express an ownership
interest in
your object,
which increments
its retain
count.
The owners
of an object
may also relinquish
their ownership
interest in it, which decrements
the retain count.
When the retain
count becomes zero,
the object
is deallocated (destroyed).
Garbage
collection is not available in iOS.
Memory-Management Rules
Memory-management rules, sometimes referred to as the ownership
policy, help you to explicitly manage memory in Objective-C
code.Memory-Management Rules
- You own any object you create by allocating memory for it or
copying it.
Related methods:
alloc
,allocWithZone:
,copy
,copyWithZone:
,mutableCopy
,mutableCopyWithZone:
- If you are not the creator of an object, but want to ensure
it stays in memory for you to use, you can express an ownership
interest in it.
Related method:
retain
- If you own an object, either by creating it or expressing an
ownership interest, you are responsible for releasing it when you no
longer need it.
Related methods:
release
,autorelease
- Conversely, if you are not the creator of an object and have not expressed an ownership interest, you must not release it.
What is the difference between retain & assign?
Assign creates
a reference
from one object to another
without
increasing
the source’s
retain count.
if
(_variable != object)
{
[_variable
release];
_variable = nil;
_variable = object;
}
Retain creates
a reference
from one object to another
and increases
the retain
count
of the
source object.
if
(_variable != object)
{
[_variable release];
_variable = nil;
_variable = [object
retain];
}
Why do we need to use @Synthesize?
Why do we need to use @Synthesize?
We
can use generated code like nonatomic, atmoic, retain without writing
any lines of code. We also have getter
and setter methods.
To use this, you have 2
other ways:
@synthesize
or @dynamic:
@synthesize,
compiler will generate the getter and setter
automatically for you, @dynamic:
you have to write them yourself.@property
is really good for memory management,
for example: retain.
How
can you do retain without @property?
if
(_variable != object)
{
[_variable
release];
_variable
= nil;
_variable
= [object retain];
}
How can you use it with @property?
self.variable
= object;
When
we are calling the above
line (same as),
we actually call the setter like
[self
setVariable:object]
and then the generated setter will do its job
What is Delegation in iOS?
Delegation
is a design
pattern
in which one
object sends messages to another
object—specified
as its delegate—to
ask for input or to notify it that an event
is occurring. Delegation is often used as an alternative
to class inheritance
to extend
the functionality of reusable objects.
For example, before a window changes size, it asks its delegate
whether the new size is ok. The delegate replies to the window,
telling it that the suggested size is acceptable or suggesting a
better size. (For more details on window resizing, see
thewindowWillResize:toSize: message.)Delegate
methods are
typically grouped
into
a protocol.
A protocol
is basically just a list
of methods.
The delegate protocol specifies all the messages an object might send
to its delegate. If
a class
conforms to (or adopts)
a protocol,
it
guarantees that it implements the required methods of a protocol.
(Protocols
may also include optional methods).In
this application, the application
object tells its delegate
that
the main
startup
routines have finished by
sending
it the applicationDidFinishLaunching:
message.
The delegate is then able to perform additional tasks if it wants.
How can we achieve singleton pattern in iOS?
The
Singleton design
pattern
ensures
a class
only has one instance,
and provides a global
point of access to it.
The class keeps track of its sole instance and ensures that no other
instance can be created. Singleton classes are appropriate for
situations where it makes sense for a single object to provide access
to a global resource.Several Cocoa framework classes are singletons.
They include NSFileManager, NSWorkspace, NSApplication,
and, in UIKit, UIApplication.
A process is limited to one instance of these classes. When a client
asks the class for an instance, it gets a shared instance, which is
lazily created upon the first request.Refer: Singleton
Pattren
A
singleton class returns the same instance no matter how many times an
application requests it.
A typical class permits callers to create as many instances of the
class as they want, whereas with a singleton
class, there can be only one instance of the class per process.
A singleton object provides a global
point of access to the resources of its class.
Singletons are used in situations where this single point of control
is desirable, such as with classes that offer some general service or
resource.
/////////////////
.h
/////////////////
#import <Foundation/Foundation.h>
@interface
MySingleton : NSObject
{
}
+ (MySingleton*) sharedInstance;
@end
/////////////
.m
////////////////
#import
“MySingleton.h”
@implementation MySingleton
static MySingleton* _sharedMySingleton = nil;
+(MySingleton*)sharedMySingleton
{
@synchronized
(self)
{
if (_sharedMySingleton == nil)
sharedMySingleton = [
[ MySingleton alloc] init
];
return _sharedMySingleton;
}
return nil;
}
//////////////////////////////////
how to call singleton class method
//////////////////////////////////
MySingleton
*sigController = [ MySingleton sharedMySingleton];
DO
NOT CALL IT LIKE THIS:
MySingleton
*sigController = [[ MySingleton alloc]init];
You obtain the global instance from a singleton class through a factory method. The class lazily creates its sole instance the first time it is requested and thereafter ensures that no other instance can be created. A singleton class also prevents callers from copying, retaining, or releasing the instance. You may create your own singleton classes if you find the need for them. For example, if you have a class that provides sounds to other objects in an application, you might make it a singleton.
Several Cocoa framework classes are singletons. They include
NSFileManager
, NSWorkspace
,
and, in UIKit, UIApplication
and UIAccelerometer
.
The name of the factory method returning the singleton instance has,
by convention, the form shared
ClassType.
Examples from the Cocoa frameworks are sharedFileManager
,
sharedColorPanel
, and sharedWorkspace
What is delegate pattern in iOS?
Delegation
is a mechanism by which a host object embeds a weak reference (weak
in the sense that it’s a simple pointer reference, unretained) to
another object—its delegate—and periodically sends messages to
the delegate when it requires its input for a task. The host object
is generally an “off-the-shelf” framework object (such as
an NSWindow or NSXMLParser object)
that is seeking to accomplish something, but can only do so in a
generic fashion. The delegate, which is almost always an instance of
a custom class, acts in coordination with the host object, supplying
program-specific behavior at certain points in the task (see Figure
4-3). Thus delegation
makes it possible to modify or extend the behavior of another object
without the need for subclassing.Refer:
delegate pattern
What is notification in iOS?
The
notification mechanism of Cocoa implements one-to-many broadcast
of messages based on the Observer pattern. Objects in a
program add themselves or other objects to a list of observers of one
or more notifications, each of which is identified by a global
string (the notification name). The object that wants to notify
other objects—the observed object—creates a notification
object and posts it to a notification center. The notification
center determines the observers of a particular notification
and sends the notification to them via a message. The methods
invoked by the notification message must conform to a certain
single-parameter signature. The parameter of the method is the
notification object, which contains the notification name, the
observed object, and a dictionary containing any supplemental
information.Posting a notification is a synchronous procedure.
The posting object doesn’t regain control until the notification
center has broadcast the notification to all observers. For
asynchronous behavior, you can put the notification in
a notification queue; control returns immediately to the
posting object and the notification center broadcasts the
notification when it reaches the top of the queue.Regular
notifications—that is, those broadcast by the notification
center—are intraprocess only. If you want to
broadcast notifications to other processes, you can use the
distributed notification center and its related API.
What is the difference between delegates and notifications?
We
can use notifications for a variety of reasons. For example, you
could broadcast a notification to change how user-interface elements
display information based on a certain event elsewhere in the
program. Or you could use notifications as a way to ensure that
objects in a document save their state before the document window is
closed. The general purpose of notifications is to inform other
objects of program events so they can respond appropriately.But
objects receiving notifications can react only after the event has
occurred. This is a significant difference from delegation. The
delegate is given a chance to reject or modify the
operation proposed by the delegating object. Observing
objects, on the other hand, cannot directly affect an impending
operation.
What is posing in iOS?
Objective-C
permits a class to entirely
replace another class within
an application. The replacing class is said to “pose as” the
target class. All messages sent to the target class are then instead
received by the posing class. There are some restrictions on which
classes can pose:
- A class may only pose as one of its direct or indirect superclasses. The posing class must not define any new instance variables which are absent from the target class (though it may define or override methods).
- No messages must have been sent to the target class prior to the posing.
- Posing, similarly to categories, allows globally augmenting existing classes. Posing permits two features absent from categories:
- A posing class can call overridden methods through super, thus incorporating the implementation of the target class
- A posing class can override methods defined in categories.
What
is atomic and nonatomic? Which one is safer? Which one is default?
You
can use this attribute to specify that accessor methods are not
atomic. (There is no keyword to denote atomic.)
nonatomic: Specifies
that accessors are nonatomic. By
default, accessors are atomic.
Properties
are atomic by default so that synthesized accessors provide robust
access to properties in a multithreaded environment—that is, the
value returned from the getter or set via the setter is always fully
retrieved or set regardless of what other threads are executing
concurrently.
If
you specify strong, copy,
or retain and
do not specify nonatomic,
then in a reference-counted environment, a synthesized get accessor
for an object property uses a lock and retains and autoreleases the
returned value—the implementation will be similar to the following:
[_internal
lock]; // lock using an object-level lock
|
id
result = [[value retain] autorelease];
|
[_internal
unlock];
|
return
result;
|
If
you specify nonatomic,
a synthesized accessor for an object property simply returns the
value directly.
Markup
and Deprecation
Properties
support the full range of C-style decorators. Properties can be
deprecated and support __attribute__ style
markup:
@property
CGFloat x
|
AVAILABLE_MAC_OS_X_VERSION_10_1_AND_LATER_BUT_DEPRECATED_IN_MAC_OS_X_VERSION_10_4;
|
@property
CGFloat y __attribute__((...));
Courtesy:
http://krish.codeworth.com/development/developer/ios-interview-questions-with-answers/
|
What is run loop in iOS ?
Run loops are part of the
fundamental infrastructure associated with threads. A run
loop is an event processing loop that you use to
schedule work and coordinate the receipt of incoming events. The
purpose of a run loop is to keep your thread busy when there is work
to do and put your thread to sleep when there is none.
Run loop management is not
entirely automatic. You must still design your thread’s code to
start the run loop at appropriate times and respond to incoming
events. Both Cocoa and Core Foundation provide run loop
objects to help you configure and manage your thread’s
run loop. Your application does not need to create these objects
explicitly; each thread, including the application’s main thread,
has an associated run loop object. Only secondary threads need to run
their run loop explicitly, however. In both Carbon and Cocoa
applications, the main thread automatically sets up and runs its run
loop as part of the general application startup process.
What is Dynamic typing?
A variable is dynamically typed
when the type of the object it points to is not checked at compile
time. Objective-C uses the id
data type to represent a
variable that is an object without specifying what sort of object it
is. This is referred to as dynamic typing.
Dynamic typing contrasts with
static typing, in which the system explicitly identifies the class to
which an object belongs at compile time. Static type checking at
compile time may ensure stricter data integrity, but in exchange for
that integrity, dynamic typing gives your program much greater
flexibility. And through object introspection (for example, asking a
dynamically typed, anonymous object what its class is), you can still
verify the type of an object at runtime and thus validate its
suitability for a particular operation.
What is the configuration file name in
iOS explain in brief ? (Or) What is plist file and explain about it
is usage?
A property list is a
representation of a hierarchy of objects that can be stored in the
file system and reconstituted later. Property lists give applications
a lightweight and portable way to store small amounts of data. They
are hierarchies of data made from specific types of objects—they
are, in effect, an object graph. Property lists are easy to create
programmatically and are even easier to serialize into a
representation that is persistent. Applications can later read the
static representation back into memory and recreate the original
hierarchy of objects. Both Cocoa Foundation and Core Foundation have
APIs related to property list serialization and deserialization.
Property List
Types and Objects
Property lists consist only of
certain types of data: dictionaries, arrays, strings, numbers
(integer and float), dates, binary data, and Boolean values.
Dictionaries and arrays are special types because they are
collections; they can contain one or multiple data types, including
other dictionaries and arrays. This hierarchical nesting of objects
creates a graph of objects. The abstract data types have
corresponding Foundation classes, Core Foundation types, and XML
elements for collection objects and value objects.
When will be the autorelease object released?
Consider we are implementing our own thread
with lot of autoreleased object. Is it mandatory to use autorelease
pool on this scenario if yes/no why?
YES.It's mandatory to have an
autorelease pool on any
thread that you create, because Cocoa
internals expect there to be one in place and you will leak
memory if it isn't there.Cocoa always expects there to be an autorelease pool available. If a pool is not available, autoreleased objects do not get released and your application leaks memory. If you send an autorelease message when a pool is not available, Cocoa logs a suitable error message.
Applications that link in Objective-C frameworks typically must create at least one autorelease pool in each of their threads.
Have you ever used automated unit
test framework in iOS? Explain in short?
Three different unit testing frameworks:- OCUnit, which is the unit testing framework built into Xcode
- GHUnit, which is a third party framework with some extra cool features
- OCMock, which helps you write mock objects to aid tricky testing scenarios
Q:
What is App Bundle?
A:
When you build your iOS app, Xcode packages it as a bundle. A bundle is a directory in the file system that groups related resources together in one place. An iOS app bundle contains the app executable file and supporting resource files such as app icons, image files, and localized content.In most cases it will work on iOS4 and iOS5. If compatibility issues will arise, it will always be unique in each case. There is no general approach to address the software compatibility issue when it comes to deprecated API's. Yes. All versions of iOS have backwards compatibility as long as feature you used have been discontinued.
What are all the difference between iOS3,
iOS4 and iOS5?
Differences Between IOS3 & IOS4Multi-tasking: helps run application background. Double-tapping the home button in iOS 4.0 displays a menu that allows users to quickly close or switch to applications that are running in the background.
Email improvements, Settings, New Applications
ios 5: Siri,newstand, cameraa aon locked screen, icloud, imessage (Device ot device mesaging) like bbm
IOS 6: faster Siri, FB, fscetime, twitter integration, reminders, bye bye google maps hello 3D maps,Passbooks
Refer: Apple iOS Versions and diffrences
Is there any garbage collector concept
available in iOS?
No, Manual memory management or
ARC. There's no garbage collector under iOS. Instead, simply use
automatic reference counting (ARC). ARC will take care of most of the
memory management for you without the runtime overhead of a garbage
collector.
What is difference between synchronous
and asynchronous in web request?
Synchronous means that you trigger your NSURLConnection
request and wait for it to be done.Asynchronous means that you can trigger the request and do other stuff while
NSURLConnection
downloads data.Which is "best"?
Synchronous is very straightforward: you set it up, fire it, and wait for the data to come back. But your application sits there and does nothing until all the data is downloaded, some error occurs, or the request times out. If you're dealing with anything more than a small amount of data, your user will sit there waiting, which will not make for a good user experience.
Asynchronous requires just a little more work, but your user can do other stuff while the request does its thing, which is usually preferable. You set up some delegate methods that let you keep track of data as it comes in, which is useful for tracking download progress. This approach is probably better for most usage cases.
What are all the instruments available in Xcode?
Instruments is a performance and analysis and testing tool for dynamically tracing and profiling OS X and iOS code. It is a flexible and powerful tool that lets you track one or more processes and examine the collected data. In this way, Instruments helps you understand the behavior of both user apps and the operating system. Instruments includes the ability to:
- Examine the behavior of one or more processes
- Record a sequence of user actions and replay them, reliably reproducing those events and collecting data over multiple runs
- Create your own custom DTrace instruments to analyze aspects of system and app behavior
- Save user interface recordings and instrument configurations as templates, accessible from Xcode
- Track down difficult-to-reproduce problems in your code
- Do performance analysis on your program
- Automate testing of your app
- Stress-test parts of your app
- Perform general system-level troubleshooting
- Gain a deeper understanding of how your app works
What is the difference between copy &
retain? When can we go for copy and when can we go for retain?
About copy - When you are using retain then you are just
increasing the retain count of the object. But when you use copy, a
separate copy (shallow copy) of the object is created. Separate means
it is a different object with retain count 1.retain -- is done on the created object, it just increase the reference count.
copy -- create a new object
retain - "Specifies that retain should be invoked on the object upon assignment. ... The previous value is sent a release message." So you can imagine assigning an NSString instance (which is an object and which you probably want to retain). So the retain count goes up by 1.
copy - "Specifies that a copy of the object should be used for assignment. ... The previous value is sent a release message." Basically same as retain, but sending -copy rather than -retain. if i remember correctly the count will go up by 1 too.
ok, now going into more detail.
Property attributes are special keywords to tell compiler how to generate the getters and setters. Here you specify two property attributes: nonatomic, which tells the compiler not to worry about multithreading, and retain, which tells the compiler to retain the passed-in variable before setting the instance variable.
In other situations, you might want to use the “assign” property attribute instead of retain, which tells the compiler NOT! to retain the passed-in variable. Or perhaps the “copy” property attribute, which makes a copy of the passed-in variable before setting.
71. What is Controller Object?
A controller object acts as a
coordinator or as an intermediary between one or more view objects
and one or more model objects. In the Model-View-Controller design
pattern, a controller object (or, simply, a controller)
interprets user actions and intentions made in view objects—such as
when the user taps or clicks a button or enters text in a text
field—and communicates new or changed data to the model objects.
When
model objects change—for example, the user opens a document stored
in the file system—it communicates that new model data to the view
objects so that they can display it. Controllers are thus the conduit
through which view objects learn about changes in model objects and
vice versa. Controller objects can also set up and coordinate tasks
for an application and manage the life cycles of other objects. The
Cocoa frameworks offer three main controller types: coordinating
controllers, view controllers (on iOS), and mediating controllers (on
OS X).
72. What is code signing?
Signing an application allows
the system to identify who signed the application and to verify that
the application has not been modified since it was signed. Signing is
a requirement for submitting to the App Store (both for iOS and Mac
apps). OS X and iOS verify the signature of applications downloaded
from the App Store to ensure that they they do not run applications
with invalid signatures. This lets users trust that the application
was signed by an Apple source and hasn’t been modified since it was
signed.
Xcode uses your digital
identity to sign your application during the build process. This
digital identity consists of a public-private key pair and a
certificate. The private key is used by cryptographic functions to
generate the signature. The certificate is issued by Apple; it
contains the public key and identifies you as the owner of the key
pair.
In order to sign applications,
you must have both parts of your digital identity installed. Use
Xcode or Keychain Access to manage your digital identities. Depending
on your role in your development team, you may have multiple digital
identities for use in different contexts. For example, the identity
you use for signing during development is different from the identity
you user for distribution on the App Store. Different digital
identities are also used for development on OS X and on iOS.
An application’s executable
code is protected by its signature because the signature becomes
invalid if any of the executable code in the application bundle
changes. Resources such as images and nib files are not signed; a
change to these files does not invalidate the signature.
An application’s signature
can be removed, and the application can be re-signed using another
digital identity. For example, Apple re-signs all applications sold
on the App Store. Also, a fully-tested development build of your
application can be re-signed for submission to the App Store. Thus
the signature is best understood not as indelible proof of the
application’s origins but as a verifiable mark placed by the signer
Refere:
App Doc for more info.
73. What is Wildcard App IDs?
A wildcard app ID allows you to
use an app ID to match multiple apps; wildcard app IDs are useful
when you first start developing new apps because you don’t need to
create a separate app ID for each app. However, wildcard app IDs
can’t be used to provision an app that uses APNS, In App Purchase,
or Game Center.
A wildcard app ID omits some or
all of the bundle ID in the search string and replaces that portion
with an asterisk character (
*
). The asterisk must always
appear as the last character in the bundle search string.
When you use a wildcard app ID,
characters preceding the asterisk (if any) must match the characters
in the bundle ID, exactly as they would for an explicit app ID. The
asterisk matches all remaining characters in the bundle ID. Further,
the asterisk must match at least one character in the bundle ID. This
table shows an example search string and how it matches some bundle
IDs but not others.
If an app id uses an
*
as the bundle ID, then the search string matches any bundle ID.
74. What
is App Bundle?
When you build
your iOS app, Xcode packages it as a bundle. A bundle
is a directory in the file system that groups related resources
together in one place. An iOS app bundle contains the app executable
file and supporting resource files such as app icons, image files,
and localized content.
From your code,
access your app’s resource files using an
NSBundle
object:- Use the
mainBundle
method ofNSBundle
to obtain your app’s main bundle object.
- Use the methods of the bundle object to obtain the location of the desired resource file.
- Open (or access) the file and use it.
The
pathForResource:ofType:
method is one of several NSBundle
methods that you can use to retrieve the location of resource files
in your bundle. The following example shows how to locate an image
file called sun.png
and create an image object. The first line gets the location of the
file in the bundle. The second line creates the UIImage
object using the data in the file at that location.- Development Basics
75. Where can you test Apple iPhone apps if you don’t have the device?
iOS Simulator can be used to test mobile applications. Xcode tool that comes along with iOS SDK
includes Xcode IDE as well as the iOS Simulator. Xcode also includes all required tools and frameworks for building iOS apps. However,
it is strongly recommended to test the app on the real device before publishing it.
76. Does iOS support multitasking? iOS 4 and above supports multi-tasking and allows apps to remain in the background until they are launched again or until they are terminated.
77. Which JSON framework is supported by iOS?
SBJson framework is supported by iOS. It is a JSON parser and generator for Objective-C. SBJson provides flexible APIs and additional control that makes JSON handling easier.
In iOS 5 Apple finally made their JSON Parser public. its natively supported, no need for 3rd party frameworks
use class NSJSonSerialization
NSArray* yourArray = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:someError]
78. What are the tools required to develop iOS applications?
iOS development requires Intel-based Macintosh computer and iOS SDK.
79. Name the framework that is used to construct application’s user interface for iOS. The UIKit framework is used to develop application’s user interface for iOS. UIKit framework provides event handling, drawing model, windows, views, and controls specifically designed for a touch screen interface.
80. Name the application thread from where UIKit classes should be used?
UIKit classes should be used only from an application’s main thread. Note: The derived classes of UIResponder and the classes which manipulate application’s user interface should be used from application’s main thread.
81. Which API is used to write test scripts that help in exercising the application's user interface elements?
UI Automation API is used to automate test procedures. Tests scripts are written in JavaScript to the UI Automation API. This in turn simulates user interaction with the application and returns log information to the host computer.
82. Why an app on iOS device behaves differently when running in foreground than in background?
An application behaves differently when running in foreground than in background because of the limitation of resources on iOS devices.
83. How can an operating system improve battery life while running an app?
An app is notified whenever the operating system moves the apps between foreground and background. The operating system improves battery life while it bounds what your app can do in the background. This also improves the user experience with foreground app.
84. Which framework delivers event to custom object when app is in foreground?
The UIKit infrastructure takes care of delivering events to custom objects. As an app developer, you have to override methods in the appropriate objects to process those events.
85. When an app is said to be in not running state?
An app is said to be in 'not running' state when:
- it is not launched.
- it gets terminated by the system during running.
86. Assume that your app is running in the foreground but is currently not receiving events. In which state it would be in?
An app will be in InActive state if it is running in the foreground but is currently not receiving events. An app stays in InActive state only briefly as it transitions to a different state.
87. Give example scenarios when an application goes into InActive state?
An app can get into InActive state when the user locks the screen or the system prompts the user to respond to some event e.g. SMS message, incoming call etc.
88. When an app is said to be in active state?
An app is said to be in active state when it is running in foreground and is receiving events.
89. Name the app sate which it reaches briefly on its way to being suspended.
An app enters background state briefly on its way to being suspended.
90. Assume that an app is not in foreground but is still executing code. In which state will it be in?
Background state.
91. An app is loaded into memory but is not executing any code. In which state will it be in?
An app is said to be in suspended state when it is still in memory but is not executing any code.
92. Assume that system is running low on memory. What can system do for suspended apps?
In case system is running low on memory, the system may purge suspended apps without notice.
93. How can you respond to state transitions on your app?
On state transitions can be responded to state changes in an appropriate way by calling corresponding methods on app's delegate object.
For example: applicationDidBecomeActive method can be used to prepare to run as the foreground app.
applicationDidEnterBackground method can be used to execute some code when app is running in the background and may be suspended at any time.
applicationWillEnterForeground method can be used to execute some code when your app is moving out of the background
applicationWillTerminate method is called when your app is being terminated.
94. List down app's state transitions when it gets launched.
Before the launch of an app, it is said to be in not running state.
When an app is launched, it moves to the active or background state, after transitioning briefly through the inactive state.
95. Who calls the main function of you app during the app launch cycle?
During app launching, the system creates a main thread for the app and calls the app’s main function on that main thread. The Xcode project's default main function hands over control to the UIKit framework, which takes care of initializing the app before it is run.
96. What is the use of controller object UIApplication?
Controller object UIApplication is used without subclassing to manage the application event loop.
It coordinates other high-level app behaviors.
It works along with the app delegate object which contains app-level logic.
97. Which object is create by UIApplicationMain function at app launch time?
The app delegate object is created by UIApplicationMain function at app launch time. The app delegate object's main job is to handle state transitions within the app.
98. How is the app delegate is declared by Xcode project templates?
App delegate is declared as a subclass of UIResponder by Xcode project templates.
99. What happens if IApplication object does not handle an event?
In such case the event will be dispatched to your app delegate for processing.
100. Which app specific objects store the app's content?
Data model objects are app specific objects and store app’s content. Apps can also use document objects to manage some or all of their data model objects.
101. Are document objects required for an application? What does they offer?
Document objects are not required but are very useful in grouping data that belongs in a single file or file package.
102. Which object manage the presentation of app's content on the screen?
View controller objects takes care of the presentation of app's content on the screen. A view controller is used to manage a single view along with the collection of subviews. It makes its views visible by installing them in the app’s window.
103. Which is the super class of all view controller objects?
UIViewController class. The functionality for loading views, presenting them, rotating them in response to device rotations, and several other standard system behaviors are provided by UIViewController class.
104. What is the purpose of UIWindow object?
The presentation of one or more views on a screen is coordinated by UIWindow object.
105. How do you change the content of your app in order to change the views displayed in the corresponding window?
To change the content of your app, you use a view controller to change the views displayed in the corresponding window. Remember, window itself is never replaced.
106. Define view object.
Views along with controls are used to provide visual representation of the app content. View is an object that draws content in a designated rectangular area and it responds to events within that area.
107. You wish to define your custom view. Which class will be subclassed?
Custom views can be defined by subclassing UIView.
108. Apart from incorporating views and controls, what else an app can incorporate?
Apart from incorporating views and controls, an app can also incorporate Core Animation layers into its view and control hierarchies.
109. What are layer objects and what do they represent?
Layer objects are data objects which represent visual content. Layer objects are used by views to render their content. Custom layer objects can also be added to the interface to implement complex animations and other types of sophisticated visual effects.
110. When do u create objects on stack and when on heap
- Creating an object on the stack frees you from the burden of remembering to cleanup(read delete) the object. But creating too many objects on the stack will increase the chances of stack overflow.
- If you use heap for the object, you get the as much memory the OS can provide, much larger than the stack, but then again you must make sure to free the memory when you are done. Also, creating too many objects too frequently in the heap will tend to fragment the memory, which in turn will affect the performance of your application
- In Objective-C, it's easy: all objects are allocated on the heap.
The rule is, if you call a method withalloc
ornew
orcopy
in the name (or you callretain
), you own that object, and you must release it at some point later when you are done with it.
- on stack the memory is more closer to the program. while on heap it takes time to load data in memory
A class is a collection of encapsulated data and custom methods. A class may hold many different kinds of data, and the class methods usually (but not always) perform action related to that data. In Objective-C, a class is usually composed of two files: an interface file and an implementation file. The interface file uses the .h file extension by convention and is where the person using the class can quickly find the methods and data members available to the class. The implementation file uses the .m file extension by convention and is where the majority of the code resides because it contains the actual implementation of all the functions declared in the interface.
So, what makes a class different from an object? What is an object? An object is an instance of a class. Think back to our example with the car in the last part of the series. Where car is the class, then myCar, dansCar, and yourCar would all be objects because they are instances of the car class.
112. Readwrite
// set methods
- (void) setVin: (NSNumber*)newVin;
- (void) setMake: (NSString*)newMake;
- (void) setModel: (NSString*)newModel;
// convenience method
- (void) setMake: (NSString*)newMake
andModel: (NSString*)newModel;
// get methods
- (NSString*) make;
- (NSString*) model;
- (NSNumber*) vin;
all the above setter and getter methods can be written in 3 lines as folls using @prperty and @sysnthesize
@property(readwrite, retain) NSString* model;
@property(readwrite, retain) NSString* model;
@property(readwrite, retain) NSNumber* vin;
@property replaces all of the interface method declarations for getters and setters, and @synthesize replaces the actual methods themselves. The getters and setters are now dynamically created and we don’t need to waste time creating them unless we need to do something really special.
@property replaces all of the interface method declarations for getters and setters, and @synthesize replaces the actual methods themselves. The getters and setters are now dynamically created and we don’t need to waste time creating them unless we need to do something really special.
- (void) setMake: (NSString*)newMake andModel: (NSString*)newModel;
only the above method wont transition to @property and @synthesize
113. retainCount
NSLog(@"retainCount for car: %d", [car retainCount]);
to check how many references an object has. It is implemented for debugging only, so an app should never go live using the retainCount method.
112.What do the plus and minus signs mean in Objective C next to a method?
113. retainCount
NSLog(@"retainCount for car: %d", [car retainCount]);
to check how many references an object has. It is implemented for debugging only, so an app should never go live using the retainCount method.
112.What do the plus and minus signs mean in Objective C next to a method?
- + methods are class methods - that is, methods which do not have access to an instances properties. Used for methods like alloc or helper methods for the class that do not require access to instance variables
- - methods are instance methods - relate to a single instance of an object. Usually used for most methods on a class
So we have an “instance” of a car, now that what do we do with it? Well, we drive it and fill it with petrol, among other things. Driving and filling with petrol apply only to the cars that we use, meaning that when we fill up a car or drive a car, we are only impacting one instance, and not all the cars in the world. Therefore, filling up the car instance is considered an instance method. Itʼs something we do to our instance and only our instance.
On the other hand, if we ask the original car class how many colors of car are available, this is a class method because we are no longer only talking about the car we drive around but all cars in general.
- (void)addGas;
The “-” indicates that this is an instance method, not a class method.
1. What is the difference between weak, strong, retain & copy ?
properties for synthesizing the property : retain / assign
- retain - it is retained, old value is released and it is assigned
- assign - it is only assigned
- strong (iOS4 = retain) - i'am the owner, you cannot dealloc this before aim fine with that = retain
- weak (iOS4 = unsafe_unretained) - the same thing as assign, no retain or release
is equal to ?@property (nonatomic, assign) NSArray * tmp;
and vice versa ?@property (nonatomic, unsafe_unretained) NSArray * tmp;
if so, which one to prefer when in iOS4, or why there is (unsafe_unretained) if its exactly same as assign?
and a delegate in iOS4 should be unsafe_unretained or assign?
you should useunsafe_unretained
. You want to show the reader of your code that you actually wanted to use weak but that this was not possible because weak is not available on the iOS version you want to deploy.
One day you will drop the support for iOS4. And then you could just search forunsafe_unretained
and replace all of them withweak
. This will be much easier than searching forassign
and figuring out if you actually meantassign
orweak.
The use ofunsafe_unretained
creates more readable and understandable code where the intentions of the developer are easier to see. Basically the same reason we useYES
instead of1.
2.
a delegate should be unsafe_unretained or assign?
a delegate should have a weak assignment. But since weak is not available on iOS4 you should use unsafe_unretained. I don't see a reason to use
assign
for anything that is not a primitive type (NSInteger, float, ...). In manual memory management we used assign because there was nothing better. But weak is much better because it sets the variable to nil when the object is deallocated.2. What are delegates ?2.1 Explain how would you implement delegate ?down vote acceptedSee this discussion
A delegate allows one object to send messages to another object when an event happens. For example, if you're downloading data from a web site asynchronously using the NSURLConnection class. NSURLConnection has three common delegates:
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error - (void)connectionDidFinishLoading:(NSURLConnection *)connection - (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
One or more of these delegates will get called when NSURLConnection encounters a failure, finishes successfully, or received a response from the web site, respectively.
Protocols are also used to provide a known set of methods for classes to call after certain events occur, such as after the user taps an annotation on a map or selects a cell in a table. The classes that implement these methods are known as the delegates of the classes that call them.Classes that support delegation do so by exposing a Delegate property, to which a class implementing the delegate is assigned. The methods you implement for the delegate will depend upon the protocol that the particular delegate adopts. For the UITableView method, you implement the UITableViewDelegate protocol, for the UIAccelerometer method, you would implement UIAccelerometerDelegate, and so on for any other classes throughout iOS for which you would want to expose a delegate.http://enroyed.com/ios/delegation-pattern-in-objective-c-and-writing-custom-delegates/4. What is re-usable identifier ?The purpose ofdequeueReusableCellWithIdentifier
is to use less memory. If the screen can fit 4 or 5 table cells, then with reuse you only need to have 4 or 5 table cells allocated in memory even if the table has 1000 entries.5. How to create PUSH certificates ?To send Push notification to an application/device couple you need an unique device token (see the ObjectiveC page) and a certificate.
Generate a Push Certificate
To generate a certificate on a Mac OS X:
- Log-in to the iPhone Developer Program Portal
- Choose App IDs from the menu on the right (or click here)
- Create an App ID without a wildcard. For example 3L223ZX9Y3.com.armiento.test
- Click the Configure link next to this App ID and then click on the button to start the wizard to generate a new Development Push SSL Certificate (Apple Documentation: Creating the SSL Certificate and Keys)
- Download this certificate and double click on aps_developer_identity.cer to import it into your Keychain
- Launch Keychain Assistant (located in Application, Utilities or search for it with Spotlight) and click on My Certificates on the left
- Expand Apple Development Push Services and select Apple Development Push Services AND your private key (just under Apple Development Push Services)
- Right-click and choose "Export 2 elements..." and save as server_certificates_bundle_sandbox.p12 (don't type a password).
- Open Terminal and change directory to location used to save server_certificates_bundle_sandbox.p12 and convert the PKCS12 certificate bundle into PEM format using this command (press enter when asked for Import Password):
- Now you can use this PEM file as your certificate in ApnsPHP!
6. How would you upload build to the appStore ?
After you archive you will have the option tosubmit
to the app store, just make sure you are using the right provisioning profile and you will be good to go.
It is useful to know xcode 4 also allows you to do the validation test before submitting so when you submit you are certain there are no problems.7. What is ARC ?http://www.raywenderlich.com/5677/beginning-arc-in-ios-5-part-1“Automatic Reference Counting (ARC) is a compiler-level feature that simplifies the process of managing object lifetimes (memory management) in Cocoa applications.”The most disruptive change in iOS 5 is the addition of Automatic Reference Counting, or ARC for short. ARC is a feature of the new LLVM 3.0 compiler and it completely does away with the manual memory management that all iOS developers love to hateYou keep programming as usual, except that you no longer call retain, release and autorelease.With Automatic Reference Counting enabled, the compiler will automatically insert retain, release and autorelease in the correct places in your program.It is important to realize that ARC is a feature of the Objective-C compiler and therefore all the ARC stuff happens when you build your app. ARC is not a runtime feature (except for one small part, the weak pointer system), nor is it *garbage collection* that you may know from other languages.Pointers Keep Objects Alive
The new rules you have to learn for ARC are quite simple. With manual memory management you needed to retain an object to keep it alive. That is no longer necessary, all you have to do is make a pointer to the object. As long as there is a variable pointing to an object, that object stays in memory. When the pointer gets a new value or ceases to exist, the associated object is released. This is true for all variables: instance variables, synthesized properties, and even local variables.
It makes sense to think of this in terms of ownership. When you do the following,
NSString *firstName = self.textField.text;
An object can have more than one owner. Until the user changes the contents of the UITextField, its text property is also an owner of the string object. There are two pointers keeping that same string object alive:
Moments later the user will type something new into the text field and its text property now points at a new string object. But the original string object still has an owner (the firstName variable) and therefore stays in memory.
Only when firstName gets a new value too, or goes out of scope — because it’s a local variable and the method ends, or because it’s an instance variable and the object it belongs to is deallocated — does the ownership expire. The string object no longer has any owners, its retain count drops to 0 and the object is deallocated.
We call pointers such as firstName and textField.text “strong” because they keep objects alive. By default all instance variables and local variables are strong pointers.
There is also a “weak” pointer. Variables that are weak can still point to objects but they do not become owners:
__weak NSString *weakName = self.textField.text;
The weakName variable points at the same string object that the textField.text property points to, but is not an owner. If the text field contents change, then the string object no longer has any owners and is deallocated:
When this happens, the value of weakName automatically becomes nil. It is said to be a “zeroing” weak pointer.
Note that this is extremely convenient because it prevents weak pointers from pointing to deallocated memory. This sort of thing used to cause a lot of bugs — you may have heard of the term “dangling pointers” or “zombies” — but thanks to these zeroing weak pointers that is no longer an issue!
You probably won’t use weak pointers very much. They are mostly useful when two objects have a parent-child relationship. The parent will have a strong pointer to the child — and therefore “owns” the child — but in order to prevent ownership cycles, the child only has a weak pointer back to the parent.
An example of this is the delegate pattern. Your view controller may own a UITableView through a strong pointer. The table view’s data source and delegate pointers point back at the view controller, but are weak. We’ll talk more about this later.
Note that the following isn’t very useful:
__weak NSString *str = [[NSString alloc] initWithFormat:...]; NSLog(@"%@", str); // will output "(null)"
You can use the __strong keyword to signify that a variable is a strong pointer:
__strong NSString *firstName = self.textField.text;
Properties can also be strong and weak. The notation for properties is:
@property (nonatomic, strong) NSString *firstName; @property (nonatomic, weak) id <MyDelegate> delegate;
For example, it was impossible to write code like this before:
id obj = [array objectAtIndex:0]; [array removeObjectAtIndex:0]; NSLog(@"%@", obj);
Automatic Reference Counting also has a few limitations. For starters, ARC only works on Objective-C objects. If your app uses Core Foundation or malloc() and free(), then you’re still responsible for doing the memory management there.
Automatic Conversion We are going to convert the Artists app to ARC. Basically this means we’ll just get rid of all the calls to retain, release, and autorelease, but we’ll also run into a few situations that require special attention.
There are three things you can do to make your app ARC-compatible:
- Xcode has an automatic conversion tool that can migrate your source files.
- You can convert the files by hand.
- You can disable ARC for source files that you do not want to convert. This is useful for third-party libraries that you don’t feel like messing with.
How to use ARC in eisting apps ?
ARC is a feature of the new LLVM 3.0 compiler. Your existing projects most likely use the older GCC 4.2 or LLVM-GCC compilers, so it’s a good idea to switch the project to the new compiler first and see if it compiles cleanly in non-ARC mode.
- Click on the Compiler for C/C++/Objective-C option to change it to Apple LLVM compiler 3.0
- set the Objective-C Automatic Reference Counting option to Yes
Enabling ARC in Your Project
To enable ARC simply set the Objective-C Automatic Reference Counting option in your Xcode project’s Build Settings to YES. Behind the scenes this sets the -fobjc-arc compiler flag that enables ARC.
New Rules Enforced by ARC
There are a few rules you need to abide by in order to compile with ARC enabled.
1. Alloc/Init Objects
As described above, creating objects is done as before, however you must not make anyretain/release/autorelease/retainCount calls. You also cannot be sneaky by calling their selectors indirectly: use of @selector(retain) and @selector(release) are prohibited.
2. Dealloc Methods
Generally these will be created for you. You must not make a dealloc call directly. However you can still create a custom dealloc method if you need to release resources other than instance variables. When creating a custom dealloc method, do not call the [super dealloc] method. This will be done for you and is enforced by the compiler.
3. Declared Properties
Before ARC, we told the compiler how to memory manage declared public properties using theassign/retain/copy parameters with the @property directive. These parameters are no longer used in ARC. Instead we have the weak/strong parameters to tell the compiler how we want our properties treated.
4. Object Pointers in C Structures
This is also a taboo. The docs suggest storing them in a class instead of a struct. This makes sense since they would otherwise be unknown to ARC. It might cause extra some migration headaches. However, ARC can be disabled on a file by file basis. See the section on “Including Code that is not ARC Compliant” below.
5. Casual Casting Between id and void*
Casting between id and void* data types is frequently done when handing objects between Core Foundation’s C library functions and Foundation Kit’s Objective-C library methods. This is known asToll Free Bridging.
With ARC you must provide hints/qualifiers to tell the compiler when CF objects are moving into and out of its control for memory management. These qualifiers include __bridge, __bridge_retain and__bridge_transfer. Also you still need to call CFRetain and CFRelease to memory manage Core Foundation objects.
This is a more advanced topic, so if you don’t know what CF objects are, don’t worry for now.
6. @autoreleasepool instead of NSAutoReleasePool
ARC compliant code must not use NSAutoReleasePool objects, instead use the @autoreleasepool{}blocks. A good example is in the main.m file of any ARC compliant/migrated project.
123456int
main(
int
argc,
char
*argv[])
{
@autoreleasepool
{
return
UIApplicationMain(argc, argv,
nil
,
NSStringFromClass
([ExampleAppDelegate
class
]));
}
}
Zone based memory is gone (apparently it’s not in the runtime anymore either); you cannot use NSAllocateObject or NSDeallocateObject.
ARC Qualifiers – Declared Properties
As programmers, we are used to making decisions like whether to make something a variable or a constant, locally or globally defined, etc. So too, we must decide how our properties relate to other objects. We use the strong/weak qualifiers to notify the compiler of these relationships.
Strong References
A strong reference is a reference to an object that stops it from being deallocated. In other words it creates a owner relationship. Whereas previously you would do this:
12// Non-ARC Compliant Declaration
@property
(retain)
NSObject
*obj;
12// ARC Compliant Declaration
@property
(strong)
NSObject
*obj;
A weak reference is a reference to an object that does not stop it from being deallocated. In other words, it does not create an owner relationship. Whereas previously you would do this:
12// Non-ARC Compliant Declaration
@property
(assign)
NSObject
*parentObj;
12// ARC Compliant Declaration
@property
(weak)
NSObject
*parentObj;
ARC Qualifiers – Regular Variables
Variable Qualifiers
The above examples illustrate declaring how our declared properties should be managed. For regular variables we have:
1234__strong
__weak
__unsafe_unretained
__autoreleasing
- __strong – is the default so you don’t need to type it. This means any object created usingalloc/init is retained for the lifetime of its current scope. The “current scope” usually means the braces in which the variable is declared (i.e. a method, for loop, if block, etc…)
- __weak – means the object can be destroyed at anytime. This is only useful if the object is somehow strongly referenced somewhere else. When destroyed, a variable with __weak is set tonil.
- __unsafe_unretained – is just like __weak but the poiner is not set to nil when the object is deallocated. Instead the pointer is left dangling (i.e. it no longer points to anything useful).
- __autoreleasing, not to be confused with calling autorelease on an object before returning it from a method, this is used for passing objects by reference, for example when passing NSError objects by reference such as [myObject performOperationWithError:&tmp];
employ the automatic conversion tool?The tool will compile the app in ARC mode and rewrites the source code for every error it encounters, until it compiles cleanly. From Xcode’s menu, choose Edit\Refactor\Convert to Objective-C ARC.
How to disable ARC for certain files?
you can do this by telling the compiler to ignore ARC for specific files, using the -fno-objc-arc flag in the Build Phases tab on the Project Settings screen. Xcode will compile these files with ARC disabled .
To enable ARC at time of creating a new project?
choose check mark Use automatic reference counting at time of creation
11. What is in-App purchase & what classes are used for in-App purchase ?12. How to create UI using .xib files ?13. What is IBAction & IBTarget ?14. How to use SQLite database in iOS apps ?
http://dblog.com.au/iphone-development-tutorials/iphone-sdk-tutorial-reading-data-from-a-sqlite-database/
On Terminal window:
cd /Users/lookaflyingdonkey/Documents mkdir SQLiteTutorial cd SQLiteTutorial sqlite3 AnimalDatabase.sql
You should now be at a “sqlite” command prompt, create table and insert data on columns
CREATE TABLE animals ( id INTEGER PRIMARY KEY, name VARCHAR(50), description TEXT, image VARCHAR(255) ); INSERT INTO animals (name, description, image) VALUES ('Elephant', 'The elephant is a very large animal that lives in Africa and Asia', 'http://dblog.com.au/wp-content/elephant.jpg'); INSERT INTO animals (name, description, image) VALUES ('Monkey', 'Monkies can be VERY naughty and often steal clothing from unsuspecting tourists', 'http://dblog.com.au/wp-content/monkey.jpg'); INSERT INTO animals (name, description, image) VALUES ('Galah', 'Galahs are a wonderful bird and they make a great pet (I should know, I have one)', 'http://dblog.com.au/wp-content/galah.jpg');
In xcode create and NSObject subclassed class animal and another UIViewController subclass UIViewAnimalController
Add framework libsqlite3.0.dylibadd AnimalDatabase.sql created earlier in resource folderin appdelegates applicationDidFinishLaunching do the foll:// Get the path to the documents directory and append the databaseNameNSArray *documentPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);NSString *documentsDir = [documentPaths objectAtIndex:0];databasePath = [documentsDir stringByAppendingPathComponent:@"AnimalDatabase.sql"]; // Execute the "checkAndCreateDatabase" function// write code to checks and see if we have already copied our database from the application bundle to the users filesystem (in their documents folder), if the database hasn’t already been created or it has been removed for some reason it will be recreated from the default database. [self checkAndCreateDatabase];// Query the database for all animal records and construct the "animals" array[self readAnimalsFromDatabase]; // here will go all the code to open sqldb astep thru each row and data add to animals class.
Story Boards - What is a story board
- With a storyboard you have a better conceptual overview of all the screens in your app and the connections between them. It’s easier to keep track of everything because the entire design is in a single file, rather than spread out over many separate nibs.
- The storyboard describes the transitions between the various screens. These transitions are called “segues” and you create them by simply ctrl-dragging from one view controller to the next. Thanks to segues you need less code to take care of your UI.
- Storyboards make working with table views a lot easier with the new prototype cells and static cells features. You can design your table views almost completely in the storyboard editor, something else that cuts down on the amount of code you have to write.
http://www.raywenderlich.com/5138/beginning-storyboards-in-ios-5-part-1
Which API is used to write test scripts that help in exercising the application's user interface elements?
A. UI Automation API is used to automate test procedures. Tests scripts are written in JavaScript to the UI Automation API. This in turn simulates user interaction with the application and returns log information to the host computer.
If u want to share data between applications or store data on device regardless of application being deleted use:
UICKeyChainStore which is similar of NSUserDefaults, alternatively you can also store data using SQLite or CoreData and then sync with iCloud on app terminate
D
atasources in uitableview
http://blog.willwinder.com/2010/10/uitableview-which-is-its-own-delegate.html
- (id) initWithFrame:(CGRect)theFrameandDataArray:(NSMutableArray*)data {if (self = [super initWithFrame:theFrame]) {// This is the "Trick", set the delegates to self.self.dataArray = data;self.dataSource = self;self.delegate = self;}return self;}#pragma mark -#pragma mark Table View Delegates- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {return 1;}- (NSInteger)tableView:(UITableView *)tableViewnumberOfRowsInSection:(NSInteger)section {return [dataArray count];}- (UITableViewCell *)tableView:(UITableView *)tableViewcellForRowAtIndexPath:(NSIndexPath *)indexPath {static NSString *CellIdentifier = @"Cell";UITableViewCell *cell =[tableViewdequeueReusableCellWithIdentifier:CellIdentifier];if (cell == nil) {cell = [[[UITableViewCell alloc] initWithFrame:CGRectZeroreuseIdentifier:CellIdentifier] autorelease];}cell.textLabel.text =[dataArray objectAtIndex:indexPath.row];return cell;}loadview and viewdidload :
If you intend to use IB to build your UI, you should do all your post IB initialization in viewDidLoad. The class will not call loadView at all if you use a nib to initialize a controller.
If you initialize the controller in code, the viewController will call loadView first, then viewDidLoad. You can do all your initialization in loadView, or viewDidLoad, depending on your preferences.
However, if you decide to use loadView, be sure to set the view property before attempting to read self.view, otherwise you will enter into an infinite loop and crash.http post and get
http://www.cimgf.com/2010/02/12/accessing-the-cloud-from-cocoa-touch/
http://panditpakhurde.wordpress.com/2009/04/16/posting-data-to-url-in-objective-c/
1. set post string with actual username and password.NSString *post = [NSString stringWithFormat:@"&Username=%@&Password=%@",@"username",@"password"];
2. Encode the post string using NSASCIIStringEncoding and also the post string you need to send in NSData format.NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];You need to send the actual length of your data. Calculate the length of the post string.NSString *postLength = [NSString stringWithFormat:@"%d",[postData length]]; 3. Create a Urlrequest with all the properties like HTTP method, http header field with length of the post string. Create URLRequest object and initialize it.NSMutableURLRequest *request = [[[NSMutableURLRequest alloc] init] autorelease];Set the Url for which your going to send the data to that request. [request setURL:[NSURL URLWithString:[NSString stringWithFormat:@"http://www.abcde.com/xyz/login.aspx"]]];Now, set HTTP method (POST or GET). Write this lines as it is in your code.[request setHTTPMethod:@"POST"];Set HTTP header field with length of the post data.[request setValue:postLength forHTTPHeaderField:@"Content-Length"];Also set the Encoded value for HTTP header Field.[request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Current-Type"];Set the HTTPBody of the urlrequest with postData.[request setHTTPBody:postData]; 4. Now, create URLConnection object. Initialize it with the URLRequest.NSURLConnection *conn = [[NSURLConnection alloc]initWithRequest:request delegate:self]; It returns the initialized url connection and begins to load the data for the url request. You can check that whether you URL connection is done properly or not using just if/else statement as below. if(conn) { NSLog(@”Connection Successful”) } else { NSLog(@”Connection could not be made”); } 5. To receive the data from the HTTP request , you can use the delegate methods provided by the URLConnection Class Reference. Delegate methods are as below.- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData*)dataAbove method is used to receive the data which we get using post method.- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)errorThis method , you can use to receive the error report in case of connection is not made to server.- (void)connectionDidFinishLoading:(NSURLConnection *)connection
How would you get data from APIs ?
You can use NSURLConnection as follows:
- Set your
NSURLRequest
: UserequestWithURL:(NSURL *)theURL
to initialise the request.
If you need to specify a POST request and/or HTTP headers, useNSMutableURLRequest
with(void)setHTTPMethod:(NSString *)method
(void)setHTTPBody:(NSData *)data
(void)setValue:(NSString *)value forHTTPHeaderField:(NSString *)field
- Send your request in 2 ways using
NSURLConnection
:- Synchronously:
(NSData *)sendSynchronousRequest:(NSURLRequest *)request returningResponse:(NSURLResponse **)response error:(NSError **)error
This returns aNSData
variable that you can process.
IMPORTANT: Remember to kick off the synchronous request in a separate thread to avoid blocking the UI. - Asynchronously:
(void)start
- Synchronously:
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response { [self.data setLength:0]; } - (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)d { [self.data appendData:d]; } - (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error { [[[[UIAlertView alloc] initWithTitle:NSLocalizedString(@"Error", @"") message:[error localizedDescription] delegate:nil cancelButtonTitle:NSLocalizedString(@"OK", @"") otherButtonTitles:nil] autorelease] show]; } - (void)connectionDidFinishLoading:(NSURLConnection *)connection { NSString *responseText = [[NSString alloc] initWithData:self.data encoding:NSUTF8StringEncoding]; // Do anything you want with it [responseText release]; } // Handle basic authentication challenge if needed - (void)connection:(NSURLConnection *)connection didReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge { NSString *username = @"username"; NSString *password = @"password"; NSURLCredential *credential = [NSURLCredential credentialWithUser:username password:password persistence:NSURLCredentialPersistenceForSession]; [[challenge sender] useCredential:credential forAuthenticationChallenge:challenge]; }
How is XML & JSON parsing done ?
in ios 4
#import "JSON/JSON.h" in yr viewcontroller
(void)viewDidLoad { [super viewDidLoad]; responseData = [[NSMutableData data] retain]; NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:@"http://www.unpossible.com/misc/lucky_numbers.json"]]; [[NSURLConnection alloc] initWithRequest:request delegate:self]; } - (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response { [responseData setLength:0]; } - (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data { [responseData appendData:data]; } - (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error { label.text = [NSString stringWithFormat:@"Connection failed: %@", [error description]]; } - (void)connectionDidFinishLoading:(NSURLConnection *)connection { [connection release];
NSString *responseString = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding]; [responseData release]; NSError *error; SBJSON *json = [[SBJSON new] autorelease]; NSArray *luckyNumbers = [json objectWithString:responseString error:&error]; [responseString release]; if (luckyNumbers == nil) label.text = [NSString stringWithFormat:@"JSON parsing failed: %@", [error localizedDescription]]; else { NSMutableString *text = [NSMutableString stringWithString:@"Lucky numbers:\n"]; for (int i = 0; i < [luckyNumbers count]; i++) [text appendFormat:@"%@\n", [luckyNumbers objectAtIndex:i]]; label.text = text; }
}
//////////////////
xml parsing steps
/////////////////
Create your parser time. You can put this wherever you want to initiate your parsing funnily enough. In my example I'm getting an XML response from a HTTP request to an API.
NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&urlResponse error:&error];
NSXMLParser *xmlParser = [[NSXMLParser alloc] initWithData:responseData];
// Don't forget to set the delegate!
xmlParser.delegate = self;
// Run the parser
BOOL parsingResult = [xmlParser parse];
in viewdidload:
NSURL *url = [[NSURL alloc] initWithString:@"http://www.example.org/blog/uploads/XML-parsing-data/Data.xml"];
parser = [[NSXMLParser alloc] initWithContentsOfURL:url];
[parser setDelegate:self];
[parser parse];
Now configure your view controller for data parsing.
I) Conforms view Controller to NSXMLParserDelegate protocol.Let your @interface implement the NSXMLParserDelegate @protocol.
II) Implement following required delegate methods of NSXMLParserDelegate into your viewcontroller .
- (void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qualifiedName attributes:(NSDictionary *)attributeDict {
}
// This delegate method gets called as a new start. In this, we allocate all data which will hold the data.
- (void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string {}
// This method gets called when parser found any character between the tags.
- (void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName {}
This delegate method gets called when parser is at the end of any tag. In this method, we compare tag names with the help of received "elementName" argument in the method and perform appropriate action on this element.
Design Pattern
MVC
; please refer other post on design patterns
Delegation;:
The delegating object is typically a framework object, and the delegate is typically a custom controller object. An example of a delegating object is an instance of the NSWindow class of the AppKit framework.
NSWindow declares a protocol, among whose methods is windowShouldClose:.
When a user clicks the close box in a window, the window object sends windowShouldClose: to its delegate to ask it to confirm the closure of the window.
The delegate returns a Boolean value, thereby controlling the behavior of the window object.
Push n local notification
Push notification: http://www.raywenderlich.com/3443/apple-push-notification-services-tutorial-part-12
http://devgirl.org/2012/10/19/tutorial-apple-push-notifications-with-phonegap-part-1/
A push notification is a short message that consists of the device token, a payload, and a few other bits and bytes. The payload is what we are interested in, as that contains the actual data we will be sending around.
Your server should provide the payload as a JSON dictionary. The payload for a simple push message looks like this:
{ "aps": { "alert": "Hello, world!", "sound": "default" } }
To enable push notifications in your app, it needs to be signed with a provisioning profile that is configured for push. In addition, your server needs. as we know
apps use different provisioning profiles for development and distribution. There are also two types of push server certificates to sign its communications to APNS with an SSL certificate. Development and distribution certificate
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions { self.window.rootViewController = self.viewController; [self.window makeKeyAndVisible]; // Let the device know we want to receive push notifications [[UIApplication sharedApplication] registerForRemoteNotificationTypes: (UIRemoteNotificationTypeBadge | UIRemoteNotificationTypeSound | UIRemoteNotificationTypeAlert)]; return YES; }
The new call to registerForRemoteNotificationTypes tells the OS that this app wants to receive push notifications.
Your app can find out which types of push notifications are enabled through:
UIRemoteNotificationType enabledTypes = [[UIApplication sharedApplication] enabledRemoteNotificationTypes];
- (void)application:(UIApplication*)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData*)deviceToken { NSLog(@"My token is: %@", deviceToken); } - (void)application:(UIApplication*)application didFailToRegisterForRemoteNotificationsWithError:(NSError*)error { NSLog(@"Failed to get token, error: %@", error); }
If you run the app in the simulator, the didFailToRegisterForRemoteNotificationsWithError: method will be called as push notifications are not supported in the simulator
Local Notifications: http://blog.mugunthkumar.com/coding/iphone-tutorial-scheduling-local-notifications-using-a-singleton-class/
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
NSLog(@"application: didFinishLaunchingWithOptions:");
// Override point for customization after application launchUILocalNotification *localNotif = [launchOptions objectForKey:UIApplicationLaunchOptionsLocalNotificationKey];if (localNotif) {
// has notifications
}
else
{
[[UIApplication sharedApplication] cancelAllLocalNotifications];
}
[window makeKeyAndVisible];return YES;}
- (void)application:(UIApplication *)application didReceiveLocalNotification:(UILocalNotification *)notif {
NSLog(@"application: didReceiveLocalNotification:");
}
- (void)applicationDidEnterBackground:(UIApplication *)application {
UILocalNotification *localNotif = [[UILocalNotification alloc] init];
localNotif.fireDate = [NSDate date]; // show now, but you can set other date to schedule
localNotif.timeZone = [NSTimeZone defaultTimeZone];
localNotif.alertBody = @"this is a notification message!";
localNotif.alertAction = @"notification"; // action button title //
//(localNotif.alertAction = NSLocalizedString(@"View details", nil);) other example;
localNotif.soundName = UILocalNotificationDefaultSoundName;
localNotif.applicationIconBadgeNumber = -1;
NSDictionary *infoDict = [NSDictionary dictionaryWithObjectsAndKeys:@"item-one",@"item", nil];
localNotif.userInfo = infoDict;
[[UIApplication sharedApplication] scheduleLocalNotification:localNotif];
[localNotif release];
}In-app purchase
Synchronization
The @synchronized directive is a convenient way to create mutex locks on the fly in Objective-C code. The @synchronized directive does what any other mutex lock would do—it prevents different threads from acquiring the same lock at the same time.
@synchronized block automatically handles locking and unlocking for you.
Synchronization Tools:
- Atomic Operations
- Memory Barriers and Volatile Variabl
es
Conditions : NSCondition, POSIX Conditions
Perform Selector Routines :
Methods Description performSelectorOnMainThread:withObject:waitUntilDone:
performSelectorOnMainThread:withObject:waitUntilDone:modes:
Performs the specified selector on the application’s main thread during that thread’s next run loop cycle. These methods give you the option of blocking the current thread until the selector is performed. performSelector:onThread:withObject:waitUntilDone:
performSelector:onThread:withObject:waitUntilDone:modes:
Performs the specified selector on any thread for which you have an NSThread
object. These methods give you the option of blocking the current thread until the selector is performed.performSelector:withObject:afterDelay:
performSelector:withObject:afterDelay:inModes:
Performs the specified selector on the current thread during the next run loop cycle and after an optional delay period. Because it waits until the next run loop cycle to perform the selector, these methods provide an automatic mini delay from the currently executing code. Multiple queued selectors are performed one after another in the order they were queued. cancelPreviousPerformRequestsWithTarget:
cancelPreviousPerformRequestsWithTarget:selector:object:
Lets you cancel a message sent to the current thread using the performSelector:withObject:afterDelay:
orperformSelector:withObject:afterDelay:inModes:
method.L
ocks : use locks to protect a critical section of your code, which is a segment of code that only one thread at a time is allowed access. How to use locks :POSIX Mutex Lock,@synchronized, NSLock Class
Lock types:
Mutex A mutually exclusive (or mutex) lock acts as a protective barrier around a resource. A mutex is a type of semaphore that grants access to only one thread at a time. If a mutex is in use and another thread tries to acquire it, that thread blocks until the mutex is released by its original holder. If multiple threads compete for the same mutex, only one at a time is allowed access to it. Recursive lock A recursive lock is a variant on the mutex lock. A recursive lock allows a single thread to acquire the lock multiple times before releasing it. Other threads remain blocked until the owner of the lock releases the lock the same number of times it acquired it. Recursive locks are used during recursive iterations primarily but may also be used in cases where multiple methods each need to acquire the lock separately. Read-write lock A read-write lock is also referred to as a shared-exclusive lock. This type of lock is typically used in larger-scale operations and can significantly improve performance if the protected data structure is read frequently and modified only occasionally. During normal operation, multiple readers can access the data structure simultaneously. When a thread wants to write to the structure, though, it blocks until all readers release the lock, at which point it acquires the lock and can update the structure. While a writing thread is waiting for the lock, new reader threads block until the writing thread is finished. The system supports read-write locks using POSIX threads only. For more information on how to use these locks, see the pthread
man page.Distributed lock A distributed lock provides mutually exclusive access at the process level. Unlike a true mutex, a distributed lock does not block a process or prevent it from running. It simply reports when the lock is busy and lets the process decide how to proceed. Spin lock A spin lock polls its lock condition repeatedly until that condition becomes true. Spin locks are most often used on multiprocessor systems where the expected wait time for a lock is small. In these situations, it is often more efficient to poll than to block the thread, which involves a context switch and the updating of thread data structures. The system does not provide any implementations of spin locks because of their polling nature, but you can easily implement them in specific situations. For information on implementing spin locks in the kernel, see Kernel Programming Guide. Double-checked lock A double-checked lock is an attempt to reduce the overhead of taking a lock by testing the locking criteria prior to taking the lock. Because double-checked locks are potentially unsafe, the system does not provide explicit support for them and their use is discouraged.
Runloops:
Run loops are part of the fundamental infrastructure associated with threads. A run loop is an event processing loop that you use to schedule work and coordinate the receipt of incoming events. The purpose of a run loop is to keep your thread busy when there is work to do and put your thread to sleep when there is none.
run
method ofUIApplication
in iOS starts an application’s main loop as part of the normal startup sequence. If you use the Xcode template projects to create your application, you should never have to call these routines explicitly.
For secondary threads, you need to decide whether a run loop is necessary, and if it is, configure and start it yourself. You do not need to start a thread’s run loop in all cases. For example, if you use a thread to perform some long-running and predetermined task, you can probably avoid starting the run loop. Run loops are intended for situations where you want more interactivity with the thread. For example, you need to start a run loop if you plan to do any of the following:
- Use ports or custom input sources to communicate with other threads.
- Use timers on the thread.
- Use any of the
performSelector
… methods in a Cocoa application. - Keep the thread around to perform periodic tasks.
Coredata :
core data is an object-c lib for database.Data management can be done using 3 options
Property lists:
Property lists (aka plists) are simple. A plist is simply a list of nested key-value pairs which can contain common data types like Strings, Numbers, Arrays and Dictionaries.
Pros: Simple to understand. Easy to work with.Cons:- Cannot run complex queries on them (at least not easily).
- You have to read the entire file into memory to get any data out of it and save the entire file to modify anything in it.
SQLite
Until CoreData came along, this was the popular way to read and write data in iPhone applications. If your a web developer, this ain’t nothing new.Procedure
Set up the SQLite database (tables and that kinda thing), set up the database connection, query the database, turn those queries into objects in your application, display object data in the UI, do some funky stuff to get object data saved back to the database.Pros
- Unlike plists, you don’t have to load the whole database up front. This makes SQLite more suitable for applications with lots of data.
- Better than plists for slicing and dicing data.
Cons
- Steeper learning curve than plists.
- Can get tedious to work with.
Core Data
Its new, its exciting, and its probably what most developers will use from here on out.I have not spent enough time with CoreData to summarize it; check out the tutorials (below) to learn more about it.Pros
- Nearly all the benefits of SQLite with a lot less hassle (Apple does a lot of the dirty work for you).
- As Apple’s preferred method it has a lot more official documentation and sample code (it seems the articles and sample code for the other two methods have mysteriously disappeared from Apple’s website).
- Probably more pros, comments please.
Cons
- Steeper learning curve than plists.
- Killer: only works on iPhone OS >3.0. Its killer if your market consists largely of iPod Touch users (who have to pay for upgrades)
coredata tutorial
http://www.cocoadevcentral.com/articles/000085.php
what is new in iOS 6
=====================================================
The Cocoa Touch Layer
UIKit Framework (UIKit.framework)
- Application lifecycle management
- Application event handling (e.g. touch screen user interaction)
- Multitasking
- Push notification in conjunction with Push Notification Service
- Local notifications (a mechanism whereby an application running in the background can gain the user’s attention)
- text fields, buttons, labels, colors, fonts
- Touch screen gesture recognition
- File sharing (the ability to make application files stored on the device available via iTunes)
- Blue tooth based peer to peer connectivity between devices
Map Kit Framework (MapKit.framework) to get a map of a specific area or to generate driving directions to get you to your intended destination
Push Notification Service: allows applications to notify users of an event even when the application is not currently running on the device, for breaking news applicaitons
Message UI Framework (MessageUI.framework) to allow users to compose and send email messages from within your application
iAd Framework (iAd.framework)to allow developers to include banner advertising within their applications
Event Kit UI Framework introduced in iOS 4 and is provided to allow the calendar events to be accessed and edited from within an application.
Twitter Framework (Twitter.framework) allows Twitter integration to be added to applications. The framework operates in conjunction the Accounts Framework to gain access to the user’s Twitter account information.
The iOS Media Layer
Core Graphics Framework (CoreGraphics.framework) Features of this framework include PDF document creation and presentation, vector based drawing, transparent layers, path based drawing, anti-aliased rendering, color manipulation and management, image rendering and gradients.
Quartz Core Framework (QuartzCore.framework)
to provide animation capabilities on the iPad. It provides the foundation for the majority of the visual effects and animation used by the UIKit framework
OpenGL ES framework (OpenGLES.framework) for high performance 2D and 3D graphics drawing
NewsstandKit Framework (NewsstandKit.framework)new feature of iOS 5 and is intended as a central location for users to gain access to newspapers and magazines
iOS Audio Support
AV Foundation framework (AVFoundation.framework) designed to allow the playback, recording and management of audio content
Core Audio Frameworks (CoreAudio.framework, AudioToolbox.framework and AudioUnit.framework) comprise Core Audio for iOS define supported audio types, playback and recording of audio files and streams and also provide access to the device’s built-in audio processing units
Open Audio Library (OpenAL) used to provide high-quality, 3D audio effects
Media Player Framework (MediaPlayer.framework) to play video in .mov, .mp4, .m4v, and .3gp formats at a variety of compression standards, resolutions and frame rates
Core Midi Framework (CoreMIDI.framework) Introduced in iOS 4, the Core MIDI framework provides an API for applications to interact with MIDI compliant devices such as synthesizers and keyboards via the iPad’s dock connector
The iOS Core Services Layer
Address Book Framework (AddressBook.framework): provides programmatic access to the iPad Address Book contact database allowing applications to retrieve and modify contact entries.
CFNetwork Framework (CFNetwork.framework): provides a C-based interface to the TCP/IP networking protocol stack and low level access to BSD sockets. This enables application code to be written that works with HTTP, FTP and Domain Name servers and to establish secure and encrypted connections using Secure Sockets Layer (SSL) or Transport Layer Security (TLS).
Core Data Framework (CoreData.framework): provided to ease the creation of data modeling and storage in Model-View-Controller (MVC) based applications. Use of the Core Data framework significantly reduces the amount of code that needs to be written to perform common tasks when working with structured data within an application.
Core Foundation Framework (CoreFoundation.framework): framework is a C-based Framework which provides basic functionality such as data types, string manipulation, raw block data management, URL manipulation, threads and run loops, date and times, basic XML manipulation and port and socket communication. Additional XML capabilities beyond those included with this framework are provided via the libXML2 library. Though this is a C-based interface, most of the capabilities of the Core Foundation framework are also available with Objective-C wrappers via the Foundation Framework.
Core Media Framework (CoreMedia.framework): is the lower level foundation upon which the AV Foundation layer is built. Whilst most audio and video tasks can, and indeed should, be performed using the higher level AV Foundation framework, access is also provided for situations where lower level control is required by the iOS application developer.
Core Telephony Framework (CoreTelephony.framework): provided to allow applications to interrogate the device for information about the current cell phone service provider and to receive notification of telephony related events.
EventKit Framework (EventKit.framework): An API designed to provide applications with access to the calendar and alarms on the device.
Foundation Framework (Foundation.framework): The Foundation framework is the standard Objective-C framework that will be familiar to those who have programmed in Objective-C on other platforms (most likely Mac OS X). Essentially, this consists of Objective-C wrappers around much of the C-based Core Foundation Framework.
Core Location Framework (CoreLocation.framework): allows you to obtain the current geographical location of the device (latitude, longitude and altitude) and compass readings from with your own applications. This will either be based on GPS readings, Wi-Fi network data or cell tower triangulation (or some combination of the three).
Store Kit Framework (StoreKit.framework): is to facilitate commerce transactions between your application and the Apple App Store. Prior to version 3.0 of iOS, it was only possible to charge a customer for an app at the point that they purchased it from the App Store. iOS 3.0 introduced the concept of the “in app purchase” whereby the user can be given the option to make additional payments from within the application. This might, for example, involve implementing a subscription model for an application, purchasing additional functionality
SQLite library: Allows for a lightweight, SQL based database to be created and manipulated from within your iPad application.
System Configuration Framework (SystemConfiguration.framework) : allows applications to access the network configuration settings of the device to establish information about the “reachability” of the device (for example whether Wi-Fi or cell connectivity is active and whether and how traffic can be routed to a server).
The iOS Core OS Layer:
The Core OS Layer occupies the bottom position of the iOS stack and, as such, sits directly on top of the device hardware. The layer provides a variety of services including low level networking, access to external accessories and the usual fundamental operating system services such as memory management, file system handling and threads.External Accessory Framework (ExternalAccessory.framework)Provides the ability to interrogate and communicate with external accessories connected physically to the iPad via the 30-pin dock connector or wirelessly via Bluetooth.
Security Framework (Security.framework) provides all the security interfaces you would expect to find on a device that can connect to external networks including certificates, public and private keys, trust policies, keychains, encryption, digests and Hash-based Message Authentication Code (HMAC).
System (LibSystem) The kernel is the foundation on which the entire iOS platform is built and provides the low level interface to the underlying hardware. Amongst other things, the kernel is responsible for memory allocation, process lifecycle management, input/output, inter-process communication, thread management, low level networking, file system access and thread management. As an app developer your access to the System interfaces is restricted for security and stability reasons. Those interfaces that are available to you are contained in a C-based library called LibSystem. As with all other layers of the iOS stack, these interfaces should be used only when you are absolutely certain there is no way to achieve the same objective using a framework located in a higher iOS layer
http://stackoverflow.com/questions/3666171/is-function-overloading-possible-in-objective-c
Method overloading is not possible in Objective-C. However, your example actually will work because you have created two different methods with different selectors:-AddMethod::
andAddMethod:
. There is a colon for each interleaved parameter. It's normal to put some text in also e.g.-addMethodX:Y:
but you don't have to.
You could start with a generic method which routes based on the type of the object you pass in.- (void)doSomething:(id)obj;
Then you can check the type to see if it's NSData or UIImage and route it internally to the appropriate methods.
- (void)doSomethingWithData:(NSData *)data; - (void)doSomethingWithImage:(UIImage *)image;
http://stackoverflow.com/questions/5431413/difference-between-protocol-and-delegates
A protocol is an interface that a class can conform to, meaning that class implements the listed methods. A class can be tested for conformance to a protocol at compile-time and also at run-time using the conformsToProtocol:.. NSObject method.A delegate is a more abstract term that refers to the Delegation Design Patten. Using this design pattern, a class would have certain operations that it delegates out (perhaps optionally). Doing so creates an alternative to subclassing by allowing specific tasks to be handled in an application-specific manner, which would be implemented by a delegate.iOS Development: What is the difference between KVO and NSNotification Center?Key-Value Observing is the process by which one object is alert to changes to another object's property.
NSNotifications are events broadcasted to the NSNotificationCenter, which delivers these events to any objects listening for that specific notification.
The difference is specificity. KVO is usually used to track specific changes to an object (i.e. a `text` property) while NSNotifications are used to track generic "events" (like a user finishing the signup flow). KVO will automatically give you useful information, such as the previous value of a property and the type of change that occurred; NSNotifications only emit whatever extra metadata you explictly specify.
You could write a KVO-esque system using NSNotifications, where every time you do something like `[object setText:@"new value"]`, a specific NSNotification is emitted. But the point of KVO is that it doesn't require the glue code you have to write for such a system.
Internally, KVO does not use NSNotificationCenter and instead does some runtime trickery to avoid said glue code; if you're interested, take a look at Mike Ash's excellent dive into KVO: http://www.mikeash.com/pyblog/fr...
tl;dr If you have many objects observing a loosely-defined event, like a user signing up or creating a new post, use NSNotificationCenter. If you have only one or a few objects that need to act on the change in another object's specific property, then use KVO.Notification requires a notification center, i.e. NSNotificationCenter. So, things from other processes are to be enqueued and it should manage them. While KVO is direct communication between objects. So, things can be faster.If you use KVO, the monitoring object, i.e. observing object, should know the key path of the observed object. The key path mean the member variable names of an observed object.Then using notification is easier because it will convey all information on what is changed from what value to what value.So, I think notification is more flexible, but it depends. Although Notification makes things easy when there are multiple object monitoring to one object and you need monitoring mechanism within different sub-system, KVO can provide more sure response because it doesn’t require a central entity, notification center. So, if you write a program which sends lots of notification messages, the chance not to receive the messages on time can become higher. Then, you will be able to replace many of them with KVO and get benefit from it.http://blog.slaunchaman.com/2011/07/19/asynchronous-synchronous-requests-effortless-networking-code/- identify basic OO concepts and the keywords Objective-C uses (interface, implementation, property, protocol, etc)
- what is a designated initializer, what is the pattern for the initializers and why ( if (self = [super ...] ) ) init, initwithlocation:setdate etc
- The Designated Initializer gives us a central point where modifications to instance creation can happen, giving us the most control over how instances are initialized. At the end of the deferment chain, there is only one method that is responsible for setting the initial state of the object, and a complete object comes out every time.
- basic memory management topics, like ownership retain/release/autorelease
- what happens if you add your just created object to a mutable array, and you release your object
- what happens if the array is released
- what happens if you remove the object from the array, and you try to use it
- If you have the object assigned to any other variable - nothing will happen. (just that the internal retain count will be decreased by one - but that's internal) If, however, the object is not assigned to any other variable, sooner or later the system will claim the memory occipied by the object. Nobody knows when this happens. That's why the object is undefined right after you remove it from the array in this case.
- You can't remove objects from a NSArray, as it is immutable. Removing objects from a NSMutableArray is straightforward:
[myMutableArray removeObject: anObject];
- trick: garbage collection on iPhone : no Garbage colection use ARC automatic reference counting. ARC is a kind of GC in that it automates memory freeing, but has a number of differences from a good garbage collector.Firstly, it's mainly a compiler technology. The compiler knows about Cocoa's reference-counting guidelines, so it inserts retains and releases where they should be according to the rules. It works just like if you'd written the retains and releases yourself — it simply inserts them for you. Normal garbage collectors keep track of your program's memory while it is running.Second, since it is just like retain and release, it can't catch retain cycles (if Object A retains Object B and Object B retains Object A, and nothing else references either of them, they both become immortal). You need to take the same precautions to prevent them
- autorelease pool usage - Autorelease pools are simply a convenience that allows you to defer sending -release until "later". That "later" can happen in several places, but the most common in Cocoa GUI apps is at the end of the current run loop cycle.
- property declarations ( assign, nonatomic, readonly, retain, copy )
- trick: ask about the nonexistent atomic keyword, what does atomic mean
- ask on how to correctly implement a retaining setter property
- ask about the circular reference problem and delegates being usually saved with assign rather then retain
- what is the difference between the dot notation and using the square brackets
- what happens when we invoke a method on a nil pointer
- difference between nil and Nil
- what is KVO and related theory + methods to use when observing
- does KVO work with ivars too?
- protocols – maybe: main difference between c#/java interface and protocols
- what to do in a situation when a class doesn’t implement a method from a protocol
- what about multiple class inheritance :use protocols
- what is fast enumeration : enumerating over the contents of a collection NSArray, NSSet, or NSDictionary.. You can use the for…in construct to enumerate the keys of a dictionary,
NSArray *array = [NSArray arrayWithObjects:@"foo", @"bar", nil]; for(NSString *string in array) { NSLog(string); }
- class methods vs instance methods
- visibility of methods
- what is an actual class in Objective-c (struct)
- ask about the isa member : what class an object is. Under the hood, Objective-C objects are basically C structs. Each one contains a field called
isa
, which is a pointer to the class that the object is an instance of (that's how the object and Objective-C runtime knows what kind of object it is). - ask about isKindOfClass isMemberOfClass
- ask about the isa member : what class an object is. Under the hood, Objective-C objects are basically C structs. Each one contains a field called
- root classes: NSObject, NSProxy
- how does proxy-ing work
- how to fake multiple class inheritance : protocols
- id type : we can send any message we like to an "
id
" variable (or aClass
variable). In fact, that's the real purpose of the "id
" type: it is the "any" type in Objective-C to which any Objective-C message may be sent- what happens during compilation if we invoke a method on an variable with the type id
- what happens runtime if the method exists
- what happens if the methods doesn’t exist
- pro and cons of using the type id
- what happens here(compile + runtime): NSString *s = [NSNumber numberWithInt:3]; int i = [s intValue];
- what are class categories and the () category
- () are extensions
- categories are used to extend functionaly of existing class without subclassing
- what is an informal protocol
- Formal and Informal ProtocolsThere are two varieties of protocol, formal and informal:
- An informal protocol is a category on NSObject, which implicitly makes almost all objects adopters of the protocol. (A category is a language feature that enables you to add methods to a class without subclassing it.) Implementation of the methods in an informal protocol is optional. Before invoking a method, the calling object checks to see whether the target object implements it. Until optional protocol methods were introduced in Objective-C 2.0, informal protocols were essential to the way Foundation and AppKit classes implemented delegation.
@interface NSObject (MyInformalProtocol) - (void)doSomething; @end ... @implementation NSObject (MyInformalProtocol) - (void)doSomething { // do something... } @end
- A formal protocol declares a list of methods that client classes are expected to implement. Formal protocols have their own declaration, adoption, and type-checking syntax. You can designate methods whose implementation is required or optional with the @required and @optional keywords. Subclasses inherit formal protocols adopted by their ancestors. A formal protocol can also adopt other protocols.
@protocol MyProtocol @required - (void)doSomething; @optional - (void)doSomethingOptional; @end ... @interface MyClass : NSObject <MyProtocol> { } @end ... @implementation MyClass - (void)doSomething { // do something... } @end
Formal protocols are an extension to the Objective-C language.An informal protocol was, as Jonnathan said, typically a category declared on NSObject with no corresponding implementation (most often -- there was the rare one that did provide dummy implementations on NSObject).As of 10.6 (and in the iPhone SDK), this pattern is no longer used. Specifically, what was declared as follows in 10.5 (and prior):@interface NSObject(NSApplicationNotifications) - (void)applicationWillFinishLaunching:(NSNotification *)notification; ... @interface NSObject(NSApplicationDelegate) - (NSApplicationTerminateReply)applicationShouldTerminate:(NSApplication *)sender; ...
Is now declared as:@protocol NSApplicationDelegate <NSObject> @optional - (NSApplicationTerminateReply)applicationShouldTerminate:(NSApplication *)sender; ... - (void)applicationWillFinishLaunching:(NSNotification *)notification; ...
That is, informal protocols are now declared as@protocol
s with a bunch of@optional
methods.In any case, an informal protocol is a collection of method declarations whereby you can optionally implement the methods to change behavior. Typically, but not always, the method implementations are provided in the context of delegation (a table view's data source must implement a handful of required methods and may optionally implement some additional methods, for example) - what is a delegate, how to create one, and use one
- what is a selector, how to do a perform selector
- how to delay executing a selector
- what to do when the selector has more paramters (NSInvocation>
performSelector:withObject:withObject:
@implementation ClassForSelectors - (void) fooNoInputs { NSLog(@"Does nothing"); } - (void) fooOneIput:(NSString*) first { NSLog(@"Logs %@", first); } - (void) fooFirstInput:(NSString*) first secondInput:(NSString*) second { NSLog(@"Logs %@ then %@", first, second); } - (void) performMethodsViaSelectors { [self performSelector:@selector(fooNoInputs)]; [self performSelector:@selector(fooOneInput:) withObject:@"first"]; [self performSelector:@selector(fooFirstInput:secondInput:) withObject:@"first" withObject:@"second"]; } @end
- how to start a selector on a background thread
performSelector:withObject:afterDelay:
- To execute the method on the current thread after a delay.performSelectorInBackground:withObject:
- To execute the method on a new background thread.performSelectorOnMainThread:withObject:waitUntilDone:
- To execute the method on the main thread.performSelector:onThread:withObject:waitUntilDone:
- To execute the method on any thread.
- how to start a thread
iOS start Background Thread
f you useperformSelectorInBackground:withObject:
to spawn a new thread, then the performed selector is responsible for setting up the new thread's autorelease pool, run loop and other configuration details –You'd probably be better off using Grand Central Dispatch, though:dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, (unsigned long)NULL), ^(void) { [self getResultSetFromDB:docids]; });
nowadays you almost can’t go wrong using Grand Central Dispatch. Running a task in background looks like this:dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{ [self doSomeLongTask]; // 1 dispatch_async(dispatch_get_main_queue(), ^{ [self longTaskDidFinish]; // 2 }); });
The long task (1) will run on some background thread and there’s no catch that I am aware of, ie. there’s already an autorelease pool in that thread, you don’t have to care about run loops etc. After the task finishes the code calls-longTaskDidFinish
on the main thread (2), so that you can update UI or whatever else. This is an often used idiom.Continuous background thread: Unless there is some specific reason this has to be a discrete thread, I would recommend you use an GCD or an NSOperation Queue and produce and consume workers. This kind of long-running thread is going to be a real problem in an iOS app.
- what is the first thing to do on a thread (autorelease pool)
- The main thread's run loop drains its pool on each pass, so it makes sense to do it on other threads too. If you choose to drain the pool only occasionally, you risk having a lot of autoreleased objects waiting to be deallocated for a long time. In fact, it depends on how much memory you can release on each pass of the run loop and how often you trigger the run loop. I always prefer to drain it on each pass just because it's easy and helps me keep the memory footprint as low as possible
- what is a runloop, and one very common place where it is used (timers, nsurlconnection)
:while(... get an event ...)
... handle event ...;
It runs on a thread; the main thread has the main event loop where user events are processed and most UI drawing, etc, occurs
run loop works by basically putting a flag in the run loop that says "after this amount of time elapses, fire the timer".
- Touches aren’t the only source of input to an iPhone application. For example, another source can be a socket – sometime you want to listen to a socket for data. But you don’t want the UI to lock up whilst it’s listening – you still want input from the user to be dealt with promptly. Similarly, you might want events to be triggered automatically at certain time intervals, but without locking up the application in the interim.A run loop is essentially an event-processing loop running on a single thread.when input comes into a particular source, the run loop will execute the appropriate code, then go back to waiting for input to come in again to any of it’s registered sources. If input comes into a registered source whilst the run-loop is executing another piece of code, it’ll finish executing the code before it handles the new input.The upside of this is that whilst you mightn’t know exactly what order things are going to come in, at least you know that they’ll be processed one after the other instead of in parallel. This means that you avoid all of those nasty multi-threading issues that were described earlier. And that’s why run loops are useful.
By default, all touch events received by an iPhone application are queued for processing by the application’s main run loop, so there’s nothing special you need to do for UI components. However, other sources of input require additional coding.To schedule an NSInputStream on a run loop,Another object that can be scheduled on a run loop is a timerWhen not to use a run loopSo when wouldn’t you use a run loop? Well, if you had some event-handling code that was going to take a long time to execute (for example, performing some CPU-intensive calculation), then everything else in the event-handling queue won’t get handled until it’s finished. This would cause your application to become unresponsive until the processing has finished. In that sort of scenario, you might want to consider using a separate thread to do the processing. - how to download something from the internet
- How to download a web page data in Objective-C on iPhone?
NSString *url = @"http://www.example.com"; NSURL *urlRequest = [NSURL URLWithString:url]; NSError *err = nil; NSString *html = [NSString stringWithContentsOfURL:urlrequest encoding:NSUTF8StringEncoding error:&err]; if(err) { //Handle }
I am developing an iPhone app for music. I want to give some options to the user so they can listen thesong/music by streaming or they can download the music in the app. I know how to stream the audio files in the app programmatically. But, i don't know how to download the audio files in the app and play the audio after download. And also user can pause the download while it is in download. Is it possible to do ? Can anyone please guide me and please share any sample code or tutorial for me? I have one more doubt: Can you please help me to create a folder inside of the app?
Creating a Folder
For every app you have a
Documents Folder
. Any files you use in your app are stored here. If you want to create more directories here, then you'd do something like this:NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0]; // Get documents folder
NSString *dataPath = [documentsDirectory stringByAppendingPathComponent:@"MyNewFolder"];
if (![[NSFileManager defaultManager] fileExistsAtPath:dataPath])
[[NSFileManager defaultManager] createDirectoryAtPath:dataPath withIntermediateDirectories:NO attributes:nil error:&error]; //Create folder if it doesn't already exist
Downloading
If you want to download audio files from the internet, then you want to look at an asynchronous method of doing it. This means that the application can carry on doing things while your download happens in the background.
For this, I recommend you use ASIHTTPREQUEST. It's great for carrying out any download requests, providing you with many options such as pausing a download (as you requested).
The website provides a great deal of documentation on downloading and storing a file. Take a look at the Downloading a File section on this page.
You'd just do something like:
NSURL *url = [NSURL URLWithString:@"http://www.fileurl.com/example.mp3"];
ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:url];
[request setDownloadDestinationPath:[NSString stringWithFormat:@"%@",dataPath]]; //use the path from earlier
[request setDelegate:self];
[request startAsynchronous];
Then just handle the progress and completion through the delegate methods that ASIHTTPRequest offers.
Playing
Playing the file is very simple. Once it's on the device and you know where it is, just load it into the audio player.
There's a great tutorial here on using AVAudioPlayer to play sounds. A very simple example of using it in your case would be:
NSURL *url = [NSURL fileURLWithPath:[NSString stringWithFormat:@"%@/audiofile.mp3",dataPath];
NSError *error;
audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:url error:&error];
if (audioPlayer == nil)
NSLog([error description]);
else
- what is the difference between a synchronous and an asynchronous request
- small task: explain how to download an image from the internet, and show this in an image view – all this after a button is tapped on the view
- you're making synchronous requests. You shouldn't be doing that on the main thread. Your best option is probably to switch to asynchronous requests. You could make synchronous requests on a background thread, but that's more complicated and unnecessary in most situations
// Get an image from the URL below** UIImage *image = [[UIImage alloc] initWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:@"yorimageurl"]]]; NSLog(@"%f,%f",image.size.width,image.size.height); **// Let's save the file into Document folder.** NSString *Dir = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0]; NSString *pngPath = [NSString stringWithFormat:@"%@/test.png",Dir];// this path if you want save reference path in sqlite NSData *data1 = [NSData dataWithData:UIImagePNGRepresentation(image)]; [data1 writeToFile:pngFilePath atomically:YES]; NSLog(@"saving jpeg"); NSString *jpegPath = [NSString stringWithFormat:@"%@/test.jpeg",Dir];// this path if you want save reference path in sqlite NSData *data2 = [NSData dataWithData:UIImageJPEGRepresentation(image, 1.0f)];//1.0f = 100% quality [data2 writeToFile:jpegFilePath atomically:YES]; NSLog(@"saving image done"); [image release];
For getting Image in Image view:UIImage *img = [UIImage imageWithContentsOfFile:yourPath]; //[UIImage imageWithData:[NSData dataWithContentsOfFile:yourPath]]; UIImageView *imgView = // Alloc + Init + Setting frame etc imgView.image = img;
- what are notifications, how to use them
- Find out which apps offer push notifications on your iDevice by going to SETTINGS on your iPhone or iPad. Once in SETTINGS, click NOTIFICATIONS (red dot).
- what is a memory warning, how do we respond to it
- Just responding to
-{application}didReceiveMemoryWarning
is enough - There are 4 levels of warnings (0 to 3). These are set from the kernel memory watcher, and can be obtained by the not-so-public function
OSMemoryNotificationCurrentLevel()
.typedef enum { OSMemoryNotificationLevelAny = -1, OSMemoryNotificationLevelNormal = 0, OSMemoryNotificationLevelWarning = 1, OSMemoryNotificationLevelUrgent = 2, OSMemoryNotificationLevelCritical = 3 } OSMemoryNotificationLevel;
How the levels are triggered is not documented. SpringBoard is configured to do the following in each memory level:- Warning (not-normal) — Relaunch, or delay auto relaunch of nonessential background apps e.g. Mail.
- Urgent — Quit all background apps, e.g. Safari and iPod.
- Critical and beyond — The kernel will take over, probably killing SpringBoard or even reboot.
Killing the active app (jetsam) is not handled by SpringBoard, but launchd.What should you do when having Memory Level Warning?Upon receiving any of these warnings, your handler method should respond by immediately freeing up any unneeded memory. For example, the default behavior of the UIViewController class is to purge its view if that view is not currently visible; subclasses can supplement the default behavior by purging additional data structures. An app that maintains a cache of images might respond by releasing any images that are not currently onscreen.How to Reduce Your App’s Memory Footprint?- Eliminate memory leaks.
- Make resource files as small as possible.
- Use Core Data or SQLite for large data sets.
- Load resources lazily.
- Build your program using the Thumb option.
- How to allocate memory wisely?
- Reduce your use of autoreleased objects : With automatic reference counting (ARC), it is better to alloc/init objects and let the compiler release them for you at the appropriate time. This is true even for temporary objects that in the past you might have autoreleased to prevent them from living past the scope of the current method.
- Impose size limits on resources : Avoid loading a large resource file when a smaller one will do. Instead of using a high-resolution image, use one that is appropriately sized for iOS-based devices. If you must use large resource files, find ways to load only the portion of the file that you need at any given time. For example, rather than load the entire file into memory, use the mmap and munmap functions to map portions of the file into and out of memory. For more information about mapping files into memory.
- Avoid unbounded problem sets : Unbounded problem sets might require an arbitrarily large amount of data to compute. If the set requires more memory than is available, your app may be unable to complete the calculations. Your apps should avoid such sets whenever possible and work on problems with known memory limits.
- when to use retainCount (Never, and why)
- Did you ever use autorelease? The value of retainCount includes only the current retain count. You have no idea whether it has been autoreleased. If you add a release now it might release again when the autorelease pool drains. NSObject retainCount is simply a "what's under the hood" curiosity and possibly debugging aid. You don't want to care what the actual value is for production. Code beyond your direct control could be retaining/releasing changing the value.
- why shouldn’t we invoke instance methods in an initializer and the dealloc
- You can't use an accessor method in an init method! The accessor asumes that the object is ready for work, and it isn't ready for work until after the init method is complete.
- When
-dealloc
is called, the contract is that it works its way up the class hierarchy to ensure the memory used by every parent class is disposed of correctly.[self dealloc]
would call your method again and give you an infinite loop.[super dealloc]
tears down whatever your superclass set up--and if that superclass isNSObject
, it also frees the memory the object occupies. The concept is that the initialization propagates from the top to the bottom of the inheiritance hierarchy to initialize all parent fields first and that the deallocation propagates from the bottom to the top to clean up all the child fields first. In yourinit
method, you always call[super init]
first and indealloc
you always call[super dealloc]
last. - NSCoding, archiving
- NSCopying, why can’t we simply use our own objects as key in a dictionary, what to do to solve the problem ( and the difference between a shallow and a deep copy)
- The copy ensures, that the values used as keys don't change "underhand" while being used as keys. Consider the example of a mutable string:
—- A bit more advanced topics —-
NSMutableString* key = ...
NSMutableDictionary* dict = [[NSMutableDictionary alloc] init];
[dict setObject: ... forKey: key];
Let's assume, that the dictionary did not copy the key, but instead just
retain
ed it. If now, at some later point, the original string is modified, then it is very likely, that you are not going to find your stored value in the dictionary again, even if you use the very same key object (i.e., the one, key
points to in the example above).
In order to protect yourself against such a mistake, the dictionary copies all keys. Implement NSCopying by retaining the original instead of creating a new copy when the class and its contents are immutable.
and
The copy returned is immutable if the consideration “immutable vs. mutable” applies to the receiving object; otherwise the exact nature of the copy is determined by the class
- what is a view, and a window
- difference between a view’s bounds and frame
- what is the resolution of the current available devices, difference between points and pixels (starting with iOS4)
- what is the responder chain, becomeFirstResponder
- what do IBOutlet and IBAction mean, what are they preprocessed to
- how do tableviews function
- what about multithreading and UIKit
- what to do when the keyboard appears and hides some parts of the UI that are important
- why should we release the outlets in viewDidUnload
- what is awakeFromNib, what is the difference between a nib and a xib
- what is a context
- the context is the central object in the Core Data stack. It’s the object you use to create and fetch managed objects, and to manage undo and redo operations. Within a given context, there is at most one managed object to represent any given record in a persistent store.A context is connected to a parent object store. This is usually a persistent store coordinator, but may be another managed object context. When you fetch objects, the context asks its parent object store to return those objects that match the fetch request. Changes that you make to managed objects are not committed to the parent store until you save the context
- what about multi threading and core data usage
- what is an NSManagedObjectId – can we save it for later if the application was stopped
- what types of stores does core data support
- what is lazy loading, how does this relate to core data, situations when this can be handy
- lazy loading loading-images-from-a-background-thread-using-blocks: use GCD
- ou could implement something like this in your cellForRowAtIndexPath:That way you load each image in the background and as soon as its loaded the corresponding cell is updated on the mainThread.
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0), ^(void) { NSData *data0 = [NSData dataWithContentsOfURL:someURL]; UIImage *image = [UIImage imageWithData:data0]; dispatch_sync(dispatch_get_main_queue(), ^(void) { UIImageView* imageView = (UIImageView*)[cell viewWithTag:100]; imageView.image = image; }); });
- how to ready only a few attributes of an entity
- what is an fetch result controller
- how to synchronize contexts
- how could one simulate an NSManagedObject (i’m thinking of the fact that all the properties are dynamic and not synthesized)
—- UIKit related —-
—- CoreData —-
How to create a TCP socket using Objective-C, check if some TCP ports are opened on the server?
or
NSStream and its subclasses NSInputStream and NSOutputStream.
To check for connectivity you may also consider to take a look at Reachability.
SKRequest SKRequestDelegate
SKProductsRequest SKProductsRequestDelegate
SKProductsResponse, SKProduct
SKPayment, SKPAymentQUeue, SKPaymenttransactrionobserver
SKPaymentTransaction
No comments:
Post a Comment