iOS经典面试题

ObjectiveC questions

1.What is category? Can you have properties or ivars in a category?

可以,但不能在非匿名类别中使用实例变量。非匿名类别中的属性不会被合成setter/getter方法。需要使用关联对象来解决。

2.What is protocol? What is formal and informal protocol?

协议是一种用于实现多态的机制,遵守协议意味着协议中规定的必须方法需要被实现。是对象能力的一种保证。调用方只要知道被调用放遵守了协议即可,无需知道被调用方是什么类型。
正式协议是使用 protocol 关键字实现的,非正式协议即NSObject类别。

3.What is ARC? Is it garbage collection?

ARC 是自动引用计数,不是垃圾收集。实质上 ARC 还是一种手动的内存管理机制。对象是否释放需要根据引用计数是否为0来判断。引用计数将对对象内存的管理集中在了对象内部。而malloc/free new/delete是在外部的。且release只会减少引用计数,并不会直接收回内存。垃圾收集是全自动的,内存完全由垃圾收集器进行管理。

4.Difference between atomic and nonatomic properties?

atomic保证了属性setter/getter方法操作的原子性(加锁),会带来一定的开销。但并不意味着线程安全。因为在当前线程第一次读取到属性的当前值,紧接着另一个线程对属性进行了修改,此时当前线程又读取该属性就会造成数据的不一致。
nonatomic是不保证原子性的,开销较少。

5.Difference between strong and retain?

没什么区别,表示强引用,就是说先释放旧的值,再赋值的同时对对象的引用计数加一。

6.What is unsafe_unretained? Difference between unsafe_unretained, assign and weak?

unsafe_unretain 不会对对象的引用计数加一,对象被释放后也不会将对象置为 nil

assign 只会对基本类型使用,表示赋值语义,不会对引用计数加一。

weak 表示弱引用,只能针对 Objective-C 对象使用,不会对引用计数加一,在对象被释放时,会自动将对象置为 nil

7.What does a copy property do? Is it deep copy or shallow copy?

copy 表示复制语义,在对属性进行复制操作时会将对象复制一份。对于不同类型的对象有着不同的拷贝方法。

对于非集合类型不可变对象copy会进行指针复制(浅复制),对非集合类型可变对象会进行内容复制(深复制),最终产生一个不可变类型的指针。所以,不可以对可变类型的属性使用 copy 修饰,将会导致可变类型属性丧失可变性,在试图对其进行修改时发生错误。

对于集合类型的不可变对象,copy会进行指针复制(浅复制)。对于集合类型的可变对象仍然只是进行浅复制只是产生了一个新的指向不可变集合对象的指针,集合对象中的元素并不会被复制(引用的还是原来集合中的对象)。

Does ObjectiveC have function overloading?

OC 不支持函数重载

8.What is messaging? How does the runtime handle message passing? What is message forwarding?

在 OC 中,调用对象的方法称为向对象发送消息,消息可以理解为是对象的方法。运行时使用objc_msgSend方法发送消息,先在对象的方法缓存中查找相关的方法,没有的话就回去对象的方法列表中去查找方法。找到后直接调用并且将方法缓存到方法缓存中。

如果对象不能处理消息,则需要启动动态方法决议机制,启动前先调用 resolveInstanceMethod: 进行动态方法解析。解析失败则进行动态方法决议,首先调用 forwardTargetForSelector: 并根据继承关系查询,如果没有处理,就调用 methodSignatureForSelector: 方法查询方法签名,并根据继承关系查询,如果在此处处理了,就会调用 forwardInvocation: 方法进行最后的处理。默认实现是抛出异常结束程序。

9.What is ‘id’?

id 是一个动态的类型,可以表示 Objective-C 中的对象。包括 NSObjectNSProxy 本类或子类。

10.What is performSelector:withObject:? What if I have to performSelector:withObject: but pass 3-4 arguments to the method? (Hint: NSInvocationOperation)

performSelector:withObject: 是运行时方法,可以通过 selector 来调用方法并且传递一个参数(其实就是根据字符串调用方法 @selector 不过是个 char*)。
使用 NSInvocation 对方法调用进行封装,可以传递任意数量的参数。

一种实现方式:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
- (id)performSelector:(SEL)aSelector withObjects:(NSArray *)objects {
NSMethodSignature *signature = [self methodSignatureForSelector:aSelector];
NSInvocation *invocation = [NSInvocation invocationWithMethodSignature:signature];
[invocation setTarget:self];
[invocation setSelector:aSelector];

NSUInteger i = 1;
for (id object in objects) {
[invocation setArgument:&object atIndex:++i];
}
[invocation invoke];

if ([signature methodReturnLength]) {
id data;
[invocation getReturnValue:&data];
return data;
}
return nil;
}

NSInvocationQueue:

1
2
3
4
5
6
7
8
9
10
11
12
13
NSInvocation* deleteInvocation = [NSInvocation invocationWithMethodSignature:[self methodSignatureForSelector:@selector(deleteDataAtPath:)]];
[deleteInvocation setTarget:self];
[deleteInvocation setSelector:@selector(deleteDataAtPath:)];//给NSInvocation对象添加对应的动作
// // self, _cmd, ... 参数索引必须是2以后
[deleteInvocation setArgument:&cachePath atIndex:2];
//用NSInvocation对象来初始化一个NSOperation的子类NSInvocationOperation对象
NSInvocationOperation *operation = [[NSInvocationOperation alloc] initWithInvocation:invoction];

//初始化一个操作队列
NSOperationQueue* operationQueue=[[NSOperationQueue alloc] init];

//在操作队列中加入操作
[operationQueue addOperation:operation];

11.What is delegate? Can delegates be retained?

代理是用来在将事情交给另外的对象来做的一种方法。代理对象必须是 weak 的,否则会造成循环引用。如果使用 retain,则要在使用过后进行释放。

12.What is retain cycle?

循环引用,不解释。。。

13.Does ObjectiveC have multiple inheritance? Why not? How to imitate multiple inheritance?

没有多重继承。会带来交叉继承的复杂性。而且容易造成超大对象。可以使用协议来模拟多重继承。

14.What is class extension? Why do we require them?

类的扩展就是写在类的实现文件中用于隐藏类的某些属性,方法声明并可以在里面添加实例变量的结构,下面是一个例子:

1
2
3
4
5
6
7
@interface TestObject ()
{
int _number;
}
@property int extensionValue;
-(void)setExtensionName:(NSString*)name;
@end

15.Who calls dealloc method? Can we implement dealloc in ARC? If yes, what is the need to do that?

在对象引用计数为0的时候,系统会在一个合适的时机去调用 dealloc 方法。ARC 中可以实现这个方法,如果程序中使用了 CoreFundation 或者 CoreGraphic 等不支持 ARC 的对象时,需要在这里释放内存。另一个情况是要在这里移除 Notification ,否则会造成意外的结果。

16.Can you write setter method for a retain property?

retain 的属性,就是需要先释放旧值,然后赋新值,并且 retain

1
2
3
4
5
- (void)setTest:(TestClass *)test
{
[_test release];
_test = [test retain];
}

17.Can you write a singleton class in ObjectiveC?

自己写吧。。。

18.What is GCD? What are advantages over NSThread?

GCD 大中枢派发。NSThread 是对 pthread 的一个抽象,每个 NSThread 对象对应一个线程。GCD 相比 NSThread 提供了更加方便的block API,并且提供了更好的封装,不需要自己管理线程的生命周期、线程同步、加锁、睡眠以及唤醒等的复杂的东西。

19.What is NSOperation and NSOperationQueue?

NSOperation 是面向对象的多线程技术。相比 GCD 对线程的控制更为灵活,NSOperationQueue 是一个线程队列

20.How does dispatch_once manages to run only once?

通过一个静态的 token 来实现,没有发现 token 的时候就执行代码,发现 token 已经存在了就不去执行了。

21.What are blocks?

22.What are NSAutoreleasePool? When to use them?

23.Does a thread created using performSelectorInBackground:withObject: creates its own autorelease
pool?

24.ObjectiveC is dynamic language? True/False, explain.

是的,完全动态,全部的方法调用都是在运行时决定的,通过 runtime 也可以在运行时进行很多反射的操作。

25.An NSArray containing Employee model object which has properties like empId, salary, age, designation, rating etc. Write a function that,

Returns average salary

Returns minimum age

Returns maximum rating

这个考的是 KVC 集合运算符,使用 valueForKeyPath: 方法就可以直接得到了。

valueForKeyPath:@"@max.salary"

valueForKeyPath:@"@min.age"

valueForKeyPath:@"@avg.rating"

29.Purpose of this question is to know if candidate knows about collection operators: Key-Value Coding Programming Guide

iOS questions

1.What is the output binary format? Explain .app structure.

2.What are the CPU architectures supported by iOS devices?

3.What iOS version onwards ARC can be used?

4.Can we support same application for iPhone3GS and iPhone5? Why not?

5.Can I write some C++ function in same .m file? Will it compile? If no, what changes should I do to compile it?

6.What are the types of iOS binaries you can create using XCode? (.app, .ipa, .a, .framework)

7.Can a static library (.a) contain resources like images, sound files etc?

8.What is bundle?

9.Explain application life cycle.

10.What is responder chain?

11.Tell me hierarchy of UIButton.

12.Why create a custom view?

13.Why UIControl is provided if we can create custom UIView?

14.What are lifecycle events of UIViewController?

15.Difference between viewDidLoad and viewDidAppear?

16.Is UIKit thread safe?

17.Why do we override drawRect: method?

18.What are layers?

19.What are various singleton instances provided by frameworks? (UIApplication, NSFileManager,
NSUserDefaults, etc.)

20.What is NSUserDefaults? What type of data can we store there?

21.How do you check if your code has memory leaks?

22.What does static analyser do?

23.What are different Instruments Xcode supports for app profiling?

24.Concepts of notification center, local and remote notifications.

25.Have you uploaded app on Appstore? What is the process?

26.Difference between Developer and Enterprise Developer accounts?

27.Common reasons for app rejection from Appstore review process?

28.UITableView cell reuse. How to get it working (w/ or w/o XIB)? How would you implement reuse on a
UIScrollView?

Few questions on CoreData which I may ask in an interview to some one brave enough to venture :)

How do you setup/initialise a core data stack in your application? Is this activity performed on main thread? If not, why?

What is NSPersistentStoreCoordinator? What duties does it perform?
What is NSPersistentStore? Is it thread safe?
What is NSManagedObjectContext? What are the different concurrency types? Explain them.
Different types of persistent stores? Which all types can we have on iOS?
Can my application have multiple models? (Yes)
In a single model, can I have few entities in one sqlite db file and remaining in another sqlite db file? (Yes, Hint: configurations)
What are the different store migration options? When are they used? How do they work? What is mapping model?
Explain parent-child context setup. How does it work? What are the advantages?
What is difference between performBlock: and performBlockAndWait:?
Are the NSManagedObjectContext queues serial or concurrent?
Can you pass same core data objects between different threads and modify?
What performance issues can you face when using CoreData?
What is NSFetchedResultsController? How do you turn on content monitoring?
How to implement “load more” using NSFetchedResultsController? (Hint: Set fetch offset and fetch limit on the NSFetchRequest of the controller, change the request to fetch more results)
What are the different delete rules that a relationship can have? Which one takes ownership?
In NSFetchRequest can we fetch only a selective few attributes of an entity? How?
Can I have relationship between entities in separate stores (in case of configurations)? (No)
What are fetched properties? How do you create a fetched property?
What does $FETCH_SOURCE and $FETCHED_PROPERTY in the predicate mean?
Why do all model object attributes get marked with @dynamic and not synthesised? What does @dynamic mean?
When a NSFetchRequest fetches an entity object from store, does it fetch all of its data at once?