This column will continue to update – iOS partners pay attention to!

(The answer is not unique, only for reference, the article has welfare at the end)

#include #import @class

  • In C, we use#includeTo import header files, used if you need to prevent repeated imports#ifndef... #define... #endif
  • In OC, we use#importTo prevent repeated introduction of header files, and avoid recursion of header files.
  • @classIt is simply used to tell the compiler that there is a class that compiles code without error and does not copy header files. Use this class if you want to use it or if you want to use an internal method#importThe import

2. What is the difference between ID and InstanceType?

  • idCan be used as method returns and parameter types can also be used to define variables
  • instancetypeCan only be used as the return value of a function or method
  • Instancetype has the advantage of being able to precisely limit the type of value returned

3. What does New do?

  1. Apply memory space to the computer (heap);
  2. Initialize instance variables;
  3. Returns the first address of the requested space;

4. Modifiers for OC instance variables? And scope of action?

@puplic

1. Member variables decorated by @public can be accessed in other classes. 2. Member variables decorated by @public can be accessed in this class. Member variables decorated with @public in their parent class can be accessed in subclassesCopy the code

@private

1. Member variable 2 decorated with @private cannot be accessed from other classes. You can also access @private member variables in this class. 3. You cannot access @private member variables in a subclassCopy the code

@protected (all instance variables are protected by default)

1. Member variable 2 decorated by @protected is not accessible from other classes. Member variable 3, decorated with @protected, can also be accessed in this class. Member variables decorated with @protected in their parent class can be accessed in subclassesCopy the code

@package

1. Something between public and private is private if accessed in another package and public if accessed in the current code.Copy the code

5. What @Proprety does

1.  @property = ivar + getter + setter;
Copy the code
  1. Help us generate it automatically in the.h filegetandsetMethod statement
  2. Help us generate private instance variables in the.m file (provided they are not generated manually in the.h file)
  3. In the.m file to help us is the implementationGet and setMethod implementation
  • Note: With @property, you can override getter and setter methods. Note that after both setter and getter methods are implemented, instance variables also need to be added manually.

6. @proprety?

  • Atomicity –atomic/nonatomicIf no, the default value isatomic(The system will automatically add synchronization lock, affecting performance), in iOS development as much as possiblenonatomic“, which helps improve the performance of the program
  • Read/write permission —Readwrite, readooly
  • Memory management semantics —Retained, assign, strong, weak, unsafe_unretained, and copy
  • The method name — — —Getter =, setter =

7 What is the difference between NSObject and ID?

  • Both NSObject and ID can point to any object
  • The NSObject object is checked at compile time and requires a cast
  • The ID type does not require compile-time checking and does not require casts

8. What is the difference between id types nil, nil,NULL and NSNULL?

  • Id type: is a unique data type that can be converted to any data type. Variables of id type can hold objects of any data type. Internally, this type is defined as a pointer to an object, which is actually a pointer to an instance variable of this object. The object declared by id has runtime properties and can point to objects of any type
  • Nil is an instance object value; If we want to set an object to null, we use nil
  • Nil is the value of a class object, if we want to set a class object to empty, Nil
  • NULL A NULL pointer to a primitive datatype (C variables have NULL Pointers)
  • NSNull is an object that is used when you cannot use nil

9. What is the difference between atomic and nonatomic?

The main difference between atomic and nonatom is that the getter/setter methods generated automatically are different

  • The getter/setter methods automatically generated by the atomic system do the locking
  • Getter /setter methods automatically generated by the nonatomic system do not lock

Atomic is not thread-safe

  • The getter/setter methods generated by the system are locked. Note that this lock is only thread-safe for getter and setter access methods.
  • Because getter/setter methods are locked, the current operation is performed before another thread can read or write the property.
  • An atomic method can ensure that an object is not destroyed by another thread while it is being accessed by multiple threads (for example, if a thread is getting or setting and another thread is releasing, it may crash).

10. What is the difference between the weak keyword and assign?

  • In ARC, when a circular reference is possible, it is often done by having one end use itweakTo solve, for example:delegateThe proxy property, which has already been strongly referenced once by itself, is also used when there is no need to strongly reference it againweak, the customIBOutletControl properties are also commonly usedweak; Of course, you can use itstrongBut it is recommended to useweak

Differences between weak and assign

  • weakPolicy When the object referred to by the property is destroyed, the system willweakModifies the pointer to a property objectnilIn theOCnilTexting shouldn’t be a problem; If you are usingassignPolicy When the object referred to by the attribute is destroyed, the pointer of the attribute object still points to the original object. Because the object has been destroyed, the wild pointer is generated at this time. If the message is sent to this object at this time, it is very likely to cause the program crashassiginCan be used to modify notOCObject, andweakMust be used forOCobject

11. Does the agent use weak or assign

  • It is recommended to useweakWeak: Indicates that the object is not responsible for keeping the delegate object. The destruction of the delegate object is controlled externally.
  • You can useassignFor assigning the delegate, you need to set the delegate pointer to nil before releasing the object; otherwise, wild Pointers will be generated

12. In ARC, what are the default keys when you do not explicitly specify any attribute keys?

  • Basic data types:atomic,readwrite,assign
  • Normal OC objects:atomic,readwrite,strong

How to use copy keyword?

  • NSString, NSArray, NSDictionary, and so on often use copyKeywords because they have corresponding mutable types:NSMutableString, NSMutableArray, NSMutableDictionaryTo ensure that the value of an attribute in an object does not change unintentionally, you should make a copy of the value when setting a new attribute to protect its encapsulation
  • blockAlso used a lotcopyKeyword, method insideblockDefault is in the stack area, usecopyYou can put it in the heap.
  • forblockusecopyorstrongThe effect is the same, but it is recommended to writecopyBecause the display tells the caller that “the compiler will automaticallyblockthecopyOperating as a

14. How do I make copy modifiers available to custom classes? How do I override a setter with the copy keyword?

If you want to copy your own objects, you need to implement the NSCopying protocol. NSCopyiog and NSMutableCopying protocols are implemented simultaneously if the custom object is divided into mutable and immutable versions

// implement immutable version copy - (id)copyWithZone:(NSZone *)zone; // implement mutable copy - (id)mutableCopyWithZone:(NSZone *)zone; - (void)setName:(NSString *)name {_name = [name copy]; }Copy the code

Do I need nil in dealloc for weak property

  • In ARC neither strong nor weak Pointers need to be set to nil in dealloc, ARC will handle it for us automatically
  • Even if the compiler doesn’t do that for us, weak doesn’t have to put nil in dealloc to clear the value of the property when the object it points to gets destroyed

16. Say something about the reflex mechanism of OC;

  • The reflection mechanism of OC is mainly based on the dynamic language characteristics of OC.
  • The System Foundation framework provides some API for method reflection;
  • We can do things like convert strings to SEL through these apis;
  • Due to the dynamic nature of the OC language, these operations occur at run time.

17. Handwritten singletons

Method one: not thread safe, if multithreading needs to lock

static ClassName *_instance; + (instancetype)sharedInstance{ @synchronized (self) { if(! _instance) { _instance = [self alloc]init]; } } return _instance; }Copy the code

GCDdispatch_once is thread safe by default

  static ClassName *_instance;
    + (instancetype)sharedInstance{
        static dispatch_one_t oneToken;
        dispatch_once(&onetoken,^{
           _instance = [self alloc]init];
        });
        return _instance;
    }

    + (instancetype)allocWithZone:(NSZone *) zone{
      static dispatch_t onetoken;
      dispatch_once(&oncetoken ^{
         _instance = [super allocwithzone:zone];
      })
      retun _instance
    }
Copy the code

18. What are zombie objects?

  • Objects that have been destroyed (objects that can no longer be used) and whose memory has been reclaimed.

19. Wild pointer

  • Pointer to zombie object (unusable memory/freed memory address)

Such as:

NSObject *obj = [NSObject new]; [obj release]; // The memory address pointed to by obj has been freed. The wild pointer error form in Xcode is usually Thread 1: EXC_BAD_ACCESS, because you are accessing a piece of memory that no longer belongs to you.Copy the code

What is a memory leak?

  • Memory leak: an object that is no longer in use but has not been destroyed and space has not been freed is called a memory leak.
  • Arc-induced loops refer to blocks, delegates,NSTimer, etc.

21. Will the elements in the array copy a new copy

  • No, the array stores the address of the previous object, will not change, you can test yourself

22. Is there any problem with the following code?

@property (copy, nonatomic) NSMutableArray * array
Copy the code

Using the copy modifier produces immutable arrays that crash when adding or deleting array elements

What is the difference between NSInteger and int in OC

  • On 32-bit operating systems, NSInteger is equivalent to int, or 32 bits
  • On 64-bit operating systems, NSInteger is equivalent to long, or 64-bit

24. What does @synthesize and @dynamic do, respectively

  • So at sign property has two words, one is@synthesize, one is@dynamic.
  • if@ synthesize and @ dynamicNone, so the default is@syntheszie var = _var;
  • @synthesizeThe semantics are if you don’t implement it manuallysetterMethods andgetterMethod, then the compiler will automatically add these two methods for you
  • @dynamicTells the compiler: propertySetter and getterMethods are implemented by the user and not automatically generated (of course, you only need to provide getters for readOnly properties)

25. What is the difference between using setValueForKey and setObjectForKey in NSMutableDictionary?

  • In general, if sent to NSMutableDictionarysetValueIt’s still calledsetObjectMethod, called if value is nilremoveObjectRemove the key-value pair;
  • setObjectForKeyNSMutableDictionary specific, value can’t be nil, otherwise it crashes
  • setValueForKeyIt’s KVC, the key has to be a string, and setObject’s key can be of any type

26. Name some ways to delay calls.

  • PerformSelector method
[the self performSelector: @ the selector (Delay) withObject: nil afterDelay: 3.0 f];Copy the code
  • NSTimer timer
[NSTimer scheduledTimerWithTimeInterval: 3.0 f target: self selector: @ the selector (Delay) the userInfo: nil repeats: NO];Copy the code
  • sleepForTimeInterval
[NSThread sleepForTimeInterval: 3.0 f];Copy the code
  • The GCD way
dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, (int64_t)(3 * NSEC_PER_SEC)); dispatch_after(popTime, dispatch_get_main_queue(), ^(void){ [self Delay]; }); - (void)Delay {NSLog(@" execute "); }Copy the code

27. What is the difference between NSCache and NSDictionary?

  1. NSCache provides automatic cache deletion and is thread-safe because, unlike dictionaries, it does not copy keys.
  2. NSCache allows you to set the cache upper limit to limit the number of objects and the total cache overhead. Defines when to delete a cached object. This mechanism is only a guide for NSCache and is not necessarily enforced.
  3. NSPurgeableData is used with NSCache to automatically clear data.
  4. Only data that is “hard to recalculate” is worth caching.

28. Difference between NSArray and NSSet

  • NSSet, like NSArray, is used to store objects, it’s a collection.
  • Nssets are “unordered sets” and are stored discontinuously in memory
  • NSArray is an ordered set that has contiguous storage locations in memory.
  • NSSet and NSArray are classes that can only add objects. If you want to add basic data types (int, float, BOOL, double, etc.), you need to encapsulate the data as NSNumber.
  • Because NSSet is implemented with hash, it makes it very fast to query, but we can’t store something after the number of elements and so on with subscripts.

29. Declare a function that takes a block function whose input and output arguments are int

- (void)test_Function:(int(^)(int num)) block{}
Copy the code

30. What is the difference between object-oriented and procedural?

  • Process-oriented: Focuses on problem-solving steps, such as C
  • Object-oriented: The focus is on solving the problem of getting those objects, and the OC language is object-oriented

31. What is the difference between object methods and class methods?

  • Object methods: start with a minus sign, can only be called by objects, can access member variables
  • Class methods: can only be called by the class name starting with a plus sign, objects cannot be called, and class methods cannot access member variables

32. What is process orientation? (POP–Procedure Oriented Programming)

  • Process Oriented(Procedure Oriented)Is a process – centered programming philosophy. Is to analyze the steps needed to solve the problem, and then use the function to implement these steps step by step, use the time one by one to call it. Focus on the implementation process!

33. What is object orientation? (OOP–Object Oriented Programming)

  • “Object oriented” is an object – centered programming idea.
  • Three main features of object orientation:
  1. Encapsulate the properties and implementation details of hidden objects, and only provide public access to the external world, which isolates changes, facilitates use, and improves reusability and security.
  2. Inheritance improves code reuse; The relationship between classes is established. A method in which a subclass can have all the member variables of its parent class; Inheritance is a prerequisite for polymorphism.
  3. A reference variable defined by a polymorphic parent class or interface can point to an instance object of a subclass or concrete implementation class. Improve the extensibility of the program.
  • Because object-oriented programming has three characteristics,Inheritance, encapsulation, polymorphism, which makes object-oriented programming easier to accept, more close to people’s life, more convenient and fast than object-oriented programming, to a certain extent, reduce the programmer’s workload, so that the readability of the program has been improved, the efficiency of the code has also been improved.

34. What is polymorphism?

  • In object-oriented language, polymorphism refers to the different implementation ways of the same interface. In OC, polymorphism refers to the different response ways of different objects to the same message. A subclass changes the implementation of the same method by overriding the parent class’s method. Embodied polymorphism
  • In plain English: polymorphism refers to a pointer to a subclass of a function (method) that calls the correct version of the function (method).
  • Polymorphism is many forms of something. Inheritance is the premise of polymorphism;

35. What is classification?

  • Classification: Without modifying the original class code, you can add a method Categroy to a class extension method, or associated attributes. The Categroy underlying structure is also a structure: it stores the name of this structure, the classification of that class, as well as the list of objects and class methods, protocols, and attribute information
  • Load all Category data for a class through the Runtime
  • I’m going to merge all the Category methods, all the attributes, all the protocol data into one big array and then the Category data that I’m going to compile later, is going to be at the front of the array
  • Inserts the merged classification data (methods, attributes, protocols) in front of the original data of the class

36. What is an agreement?

  • Protocol: A protocol is a standard that declares many methods, but does not care how the methods are implemented. The implementation is done by the classes that follow the protocol.
  • In OC, a class can implement multiple protocols, which can compensate for the defects of single inheritance. However, unlike inheritance, a protocol is just a list of methods, and the implementation of methods depends on the classes that follow the protocol.

37. Formal agreement vs. Informal Agreement?

  • Informal protocols: Any classes that add categories (categories) to NSObject or its subclass Foundation framework are informal protocols
  • Official protocol: @protocol

38. How to implement multiple inheritance?

  1. category
  2. agreement
  3. Message forwarding (more on that later)

39. Why is OC a dynamic language?

  • Dynamic language: a program can change its structure at runtime, new functions can be introduced, existing functions can be deleted, and other structural changes
  • Dynamically typed languages: Type checking is done at run time.

The dynamic characteristics of OC can be divided into three aspects:

  • Dynamic typing: Ultimately determining that the instance type of this class is at run time
  • Dynamic binding: The method to call is determined at run time
  • Dynamic loading: Loading required resources or executable code during runtime

40. Dynamic binding?

  • Dynamic binding also postpones the determination of invoked methods until runtime. OC can skip compilation and dynamically add function calls at run time, and decide at run time what methods to call and what parameters to pass in. This is called dynamic binding.
  • At compile time, method calls are not tied to the code, and the code being called is identified only after cancellation is sent. Using dynamic typing and dynamic binding techniques,

41. What are Cocoa and Cocoa Touch? The difference between them?

  • Cocoa contains the Foundation and AppKit frameworks for developing applications for Mac OS X.
  • Cocoa Touch contains the Foundation and UIKit frameworks for developing iPhone OS applications.
  • Cocoa is the development environment for Mac OS X and Cocoa Touch is the development environment for iPhone OS.

Cocoa Touch Underlying technology Architecture?

The cocoa Touch underlying technology architecture is divided into four main layers:

  • Cocoa Touch: UI components, Touch events and event drivers, system interfaces
  • Media layer: Audio and video playback, animation,2D and 3D graphics
  • Core Server: Core service layer, underlying features, files, network, location service area, etc
  • Core OS: Memory management, underlying network, hard disk management

43. What is a predicate?

Predicate (NSPredicate) is a logical selection condition of OC for data set, like a filter, simple code is as follows:

Person * p1 = [Person personWithName:@"alex" Age:20]; Person * p2 = [Person personWithName:@"alex1" Age:30]; Person * p3 = [Person personWithName:@"alex2" Age:10]; Person * p4 = [Person personWithName:@"alex3" Age:40]; Person * p5 = [Person personWithName:@"alex4" Age:80]; NSArray * persons = @[p1, p2, p3, p4, p5]; NSPredicate *predicate = [NSPredicate predicateWithFormat:@"age < 30"]; / / use the predicate filter element in the array, returns after filtering the results of the query NSArray * array = [persons filteredArrayUsingPredicate: predicate];Copy the code

44. What is a factory-like method?

A class factory method is a class method used to quickly create an object. It can directly return an initialized object with the following characteristics:

  1. It must be a class method
  2. The return value must be of type ID/InstanceType
  3. The canonical method name specifies what object a class factory method returns, usually starting with a lowercase letter of the class name.

For example, the buttonWithType method of UIButton is a class factory method:

// class factory method + (instancetype)buttonWithType:(UIButtonType)buttonType; / / use + UIButton * button = [UIButton buttonWithType: UIButtonTypeCustom];Copy the code

45. What is sugar-coated grammar?

Sugar-coated syntax, also known as syntactic sugar or syntactic salt, refers to the addition of certain syntax to a computer language that has no effect on the language’s functions, but is more convenient for programmers to use, increases the readability of programs, and reduces the chance of errors in code

OC literals are grammatical sugar

NSNumber * number = @1;
NSArray * array = @[@1, @2, @3];
NSDictionary * dict = @{@"key":@"value"};
NSNumber * num1 = array[0];
NSString * value = dict[@"key"];
Copy the code

46. Difference between Svn and Git

  • Both SVN and Git are used for project version control and code management. Monitor changes to code and resources. Conducive to the realization of efficient team cooperation;
  • SVN is centralized, which means that there is only one remote version repository. Git is distributed, which includes local and remote version repositories. The local repository keeps a complete backup of the entire project. If the server where the remote repository is stored is down, everyone’s code cannot commit, or even the repository is lost, git doesn’t have this problem because it has a local repository.
  • The branch of SVN is a complete directory that contains all the actual files. The branch of SVN is synchronized with the central repository. If a team member creates a branch, it will be synchronized to all the release members, and everyone will be affected. Branches created under Git don’t affect anyone until they merge. Creating a branch allows you to do anything locally and offline. After testing, merge into the main branch before other members can see it.

47. Is there a two-dimensional array in OC? How to do that?

There is no two-dimensional array in OC. Two-dimensional arrays can be realized by nesting one-dimensional arrays.

/ / literal definition NSArray * array = @ [@ [@ 1, @ 2, @ 3, @ 4, @ 5], @ [@ 11 @ 12, @ 13, 14, @ @ 15], @ [23, 22, 21, @ @ @ @ 24, @ 25]. @ [33, 32, 31, @ @ @ @ 34, 35] @, @ [43, 42, 41, @ @ @ @ 44, 45] @,]; / / access NSLog (@ "% @", array [1] [1]).Copy the code

48. CocoaPods understanding

CocoaPods is an ObjC dependency management tool, which itself is built using Ruby’s dependency management gems

  • To learn more about how to execute this command, add –verbose after it. Now run the command pod install –verbose
  • CocoaPod tripartite library, will compile first

49. What are the use of –verbose and –no-repo-update?

  • Verbose means long and verbose, usually used in a program to show detailed information. This parameter shows what happens during command execution.
  • Pod Install or POD update may get stuck in the Analyzing Dependencies step because these two commands upgrade CocoaPods spec repository. Append this parameter to skip this step and improve command execution speed.

50. Set operators in KVC

  1. Simple set operators: @avg, @sum, @max, @min, @count (only for collection objects, object attributes must be numeric)
  2. Object operator: @unionofObjects: an array that returns the values of the specified property, unrepeatable. @distinctUnionofObjects: an array that returns the values of the specified property
  3. Array/collective operators: Much like object operators, but work in a collection of NSArray and NSSet. @distinctUnionofSets: Returns an array consisting of the elements of each subarray without reduplicate @distinctUnionofSets: returns an array consisting of the elements of each subarray without reduplicate Similar to @distinctunionofArrays except that it expects an NSSet with an NSSet object in it and will return an NSSet object. Because collections cannot have duplicate values, there are only distinct operations.

51. What is the definition and use of const, macro,static,extern?

const

The const constant modifier, a string constant that is often used, is usually macros, but Apple doesn't recommend macros. It recommends const constants. Const int b = 5; const int b = 5; int const b = 5; Const int *p = &a and const *q = &a; The value of *p cannot be changed, but the direction of p can be changed; Int * const p = &a; Const int * const p = &a; const int * const p = &a; Const is to the left of *, pointing to mutable, const is to the right of *, pointing to immutable, const is to the right of *, pointing to immutable, const is to both sides of *Copy the code

The macro

Basic concept: macros are a term for batch processing. Generally speaking, a macro is a rule or pattern, or syntactic substitution, that explains how a particular input (usually a string) is converted to a corresponding output (usually a string) according to predefined rules. This substitution occurs at precompilation time and is called macro expansion. The compiler scans the code before compiling, and if it encounters a macro that we've already defined, it replaces the code. It just copies the macro in memory and replaces it globally. Macros are generally divided into object macros and function macros. The downside of macros: Using macros extensively in your code can lead to longer precompilation times. What's the difference between const and macro? * Compile-check macros do not have compile-check, const has compile-check; * Macros define functions, const methods do not; * Disadvantages of macros Extensive use of macros can lead to long precompilation timesCopy the code

static

Static modifies a local variable, which extends the lifetime of the entire application, and only allocates memory once. Static modifies a global variable, which only applies to the current fileCopy the code

extern

If an extern global variable is declared in a. H file, the assignment to the global variable in a. M file in the same class must be the data type + variable name (as declared) =XXXX structure. And when you call it, you must import the.h file. H @interface ExternModel: NSObject Extern NSString *lhString; @end .m @implementation ExternModel NSString *lhString=@"hello"; For example, in viewController.m, externmodel. h can be used, otherwise the global variable will not be recognized. It can also be called without importing a header file (through an extern call).Copy the code

52. What is the difference between compiled and interpreted?

  • Compiled languages: source code is first compiled to generate machine instructions, and machine code (binary) is run by the machine.
  • Interpreted languages: source code is not translated directly into machine instructions, but is first translated into intermediate code, which is then interpreted and run by the interpreter.

53. Dynamic and static languages?

  • Dynamically typed languages: Data type checking is done at run time. Instead of assigning a data type to a variable when programming in a dynamically typed language, the language records the data type internally when you first assign to a variable.
  • Statically typed languages: Data type checking is done before run time (such as compile time).

54. What are pointer constants and constant Pointers?

  • A constant pointer is essentially a pointer, and a constant modifies it to indicate that the pointer is a pointer to a constant (variable). The object to which the pointer points is a constant cannot be changed.
  • A pointer constant is essentially a constant, and to modify it with a pointer means that the value of this constant should be a pointer. The value of a pointer constant is a pointer, which cannot be assigned because it is a constant

55. Pointer functions and function Pointers

Pointer to the function

  • Pointer function: As the name implies, it is essentially a function, but its return value is a pointer.
Int *sum(int a, int b){int result = a + b; int *c = &result; return c; } int *p = sum(10, 20); printf("sum:%d\n", *p);Copy the code

A function pointer

  • Unlike a pointer function, a function pointer is essentially a pointer whose address points to a function, so it is a pointer to a function.
Int Max (int a, int b){return (a > b)? a:b; } int (*p)(int, int) = max; int result = p(10, 20); printf("result:%d\n", result);Copy the code

56. Write a standard macro MAX that takes two arguments and returns the maximum one

#define Max(a,b) a>b? a:bCopy the code

#define MIN(A,B) A<B? A:B code run result?

float a = 1; The float b = MIN (+ 1.5); Ask a =? b = ? Answer: A = 3; B = 2 + execution after the meeting, appeared in the expression + 2 times, 3, + < 1.5, returning to + 2 / / extension float a = 1; Float b = [self getMix:a++ b:1.5]; float b = [self getMix:a++ b:1.5]; - (CGFloat)getMix:(CGFloat ) a b:(CGFloat)b{ return a>b? a:b; } run a = 2; b =1;Copy the code

Next entry:

IOS Interview: OC Basics (2)

More:

Want to enter big factory, the interview question is indispensable! (iOS Interview collection!)

An iOS developer learning path guide