Questions for iOS base plane

Source: Internet
Author: User
Tags http post object serialization posix semaphore sprintf

Recently quit, find a job, light will do the project, the foundation is not familiar, today summed up a few questions.

Don't say much nonsense, go to the question:

What are the numeric objects in 1.objective-c, and what are their differences from the basic data types?

The basic type is the same as C, which is mainly int, long, double, float, char, void, bool. For basic data types, you do not need to use pointers.
NSNumber is an OC numeric object that needs to be considered for memory release.
Number types are: Nsinteger, cgfloat. The data object has nsnumber. The difference between an object and a variable. can be disassembled effect.
Other types have nsstring and nsmutablestring,nsstring are immutable strings, and the variables and basic types do not need to be released manually. of his
Retaincount is-1. Retaincount: As we all know, in iOS, we use reference counting to implement memory management, when an object is anywhere
It is automatically released when it is not referenced. This time Retancount is 0. and provides a-(Nsinteger) Retaincount method to
Implementation gets the number of objects held. nsnumber* number = [NSNumber numberwithint:1]; NSLog (@ "%lu", [number Retaincount]);
Nsarray is an immutable array that is typically used to hold fixed data. Nsmutablearray is a mutable array. can be operated directly.
Nsset is an immutable collection, and Nsmutableset is a mutable collection. A collection is a set of single-valued operations.
Nsdictionary is a collection of data for a key-value pair. Nsmutabledictionary is a variable set of data key-value pairs. All need to consider memory release issues.
Dictionary are sorted by key.
2. Using the NSLog function to output a floating-point type, the result is rounded and a decimal is retained.
CGFloat number = 3.1415926;
NSLog ("@0.1f", number);
3. Extract the data from the front and back of the ' | ' character in the string "20|http://www.621life.com" and export them separately.
nsstring* normalstring = @ "20|http://www.621life.com";
nsarray* array = [normalstring componentseparatedbystring:@ "|"];
NSLog (@ "%@ and%@", array[0],array[1]);
The Dictionary object in 4.objective-c, which is the variable Dictionary object, initializes a variable Dictionary object with two key-value pairs, and dynamically adds and
Deletes a record, outputting the first record.
Nsdictionary and Nsmutabledictionary.
nsmutabledictionary* dictionary = [nsmutabledictionary dictionarywithobjectsandkeys:@ "Val1", @ "Key1", @ "Val2", @ "Key2 "];
nsenumerator* enumerator = [Dictionary keyenumerator];
ID key = [enumerator nextobject];
while (key)
{
ID object = [dictionary Objectforkey:key];
NSLog (@ "Value:%@,key:%@",, key);
key = [Enumerator nextobject];
}
add element:
[Dictionary setobject:@ "Val3" forkey:@ "Key3"];
To delete an element:
[Dictionary removeobjectforkey:@ "Key1"];
Note: When Nectobject is called, it is copied again, or the pointer points to the end.
5. Get the project root path and under it create a directory named UserData.
nsstring* RootPath = Nshomedirectory ();
nsstring* path = [RootPath stringbyappendingstring:@ "path"];
nsfilemanager* FileManager = [Nsfilemamager Defaultmanager];
if (![ Filemanger Fileexistsatpath:path])
{
Create
[FileManager Createdirectoryatpath:path];
}
6. In the method of an object: Self.name = "Object"; Is it different from name = "Object"?
Self.name= "Object", this will increase the reference count, the hermit calls the Set method, if you rewrite the set
method, do not use this way, the syntax will be dead loop. will increase the retaincount. Name= "Object", directly assigned value,
The reference count does not change.
7. When defining attributes, what happens when using copy,assign, and retain.
Assign is a data type when called, retain and Copy user objects, copy is mainly when a points to an object, B also want to point to him when the time appears.
If you release with Assign,a, the software crashes when you call B. If copy, A and B have their own memory, a releases, B does not crash.
If you use retain, the count will increase or you can call it. In addition, atomic and nonatomic are used to determine compiler-generated setting and getting
Whether it is an atomic operation. In the case of multithreading, atomic operations are required. Failure to do so may cause an error message.
8.ViewController of Viewdidload,viewdidunload,dealloc,viewwillappear,viewwilldisappear.
(1) Viewdidload only the view is called when the nib file is loaded.
(2) Viewdidunload is called when the system memory is tight, and in this method, all Iboutlet are set to nil, and the method releases
Other view-related objects, other objects created at run time but not system, objects created in viewdidload, cached data, etc. release
Object, set the object to nil.
(3) Dealloc: This method is
Process: Loadview/nil to load View into memory, Viewdidload function to further initialize these view, when memory is low, call Viewdidunload
To release the memory data, and when used, back to the first step.
(4) Viewwillappear This method occurs when the view is about to be called. In general this time with the agent to compare a little more.
(5) Viewwilldisappear This is called when it is about to disappear.
9. Write a method that sends a synchronous HTTP request and gets the result returned.
Synchronization method:
nsmutableurlrequest* request = [[Nsmutablerequest alloc] init];
[Request Seturl:[url rulwithstring:@ "http://www.baidu.com"];
[Request sethttpmethod:@ "GET"];
nsdata* data = [nsurlconnection sendsynchronousrequest:request returnresponse:nil Error:nil];
10. How to start a new thread, how the child thread refreshes the main UI.
Determine if a thread is not the main path.
if ([Nsthread Ismainthread])
iOS, only the main thread can immediately refresh the UI, usually we put in the main thread,
Dispatch_sync (Dispatch_get_main_queue (), ^{
Implementing information
});
11. Briefly describe the implementation mechanism of OBJECTIVE-C memory management, and briefly describe when you are responsible for releasing the object and when it is not released by you.
OC inside use Retaincount to manage objects, when sending retain, the reference count will automatically add one, when the Retaincount is 0
, the system automatic bar with release, will be automatically released, when an object uses the following actions, he has the use of permissions: Alloc, Allocwithzone,
Copy, Copywithzone, Mutablecopy, Mutablecopywithzone. If you do not create an object or copy it, but retain the reference, you also have permissions
Retain After IOS4.0, arc is automatically used to manage the memory, and the compiler automatically uses retain, release, Autorelease to
Implements memory management information for the project.
12. What is the definition of the class and what is the suffix of the declaration file?
Inside iOS, the declaration of the class is in the. h file, and the implementation is in the. m file.
13. How do I automatically generate properties and how to get them?
In iOS, in the present case, you can not automatically write the set and get method, in the. h file to define variables, in the. m file directly Add _ variable can be.
You can also use @synthesize.
14. Declare a static method and an instance method.
The + symbol represents the method that represents the class,-the representation, representing the instance method. The static method has long-lived memory, but the instance method is not, so the static method is efficient but the station
Memory, instance method in contrast, loading speed and actual and memory almost no difference. Static methods allocate memory in the heap, and instance methods allocate memory on the stack.
An instance method is used to create an object first, but a static method is a method of a class that can be used directly by the class. Use a static method for the more mundane,
Static methods modify the state of the class, but the instance method modifies the information for each object. The instance method of a class is when the class disappears, the object does not,
There are no instances, but the static method, as long as you reference this space, will always exist this method.
15. What is MVC and how do you use it when you work?
MVC, views, models, controllers. View views, data JSON object models, controller controllers, view, and model have never communicated.
The most classic form between view and controller is Iboutlet, which is also useful in the case of pure code implementations.
#define Squake (a) ((a) * (a))
int a=5;
int b;
b = Squake (a++);
At this time: b=__30___
Answer 30
Parsing: #define Squake (A) ((5) * (6))
17. The modalities for inter-process communication are
1. Pipelines: Used to communicate between processes with some affinity, allowing a process to communicate with another process that has a common ancestor with him.
2. Named pipes: Named Pipes overcome the limitations of the pipe without a name, so that, in addition to having the functionality of a pipe, it also allows affinity-free
Communication between relational processes. Named pipes have corresponding file names in the file system. Named pipes are created by command Mkfifo or by system call Mkfifo.
3. Signal signal: Signal is a more complex mode of communication, used to notify the receiving process of an event occurred, in addition to inter-process communication, the process
You can also send a signal to the process itself; Linux supports signals that conform to the POSIX.1 standard in addition to the UNIX early signal semantic function Sigal
function sigaction (in fact, the function is based on BSD, BSD in order to achieve a reliable signal mechanism, but also able to unify the external interface, with Sigaction
function to re-implement the signal function).
4. Messages Message Queue: Message Queuing is a linked table of messages, including POSIX Message Queuing system V Message Queuing. Processes that have sufficient permissions can
Adds a message to the queue, and the process that is given Read permission can read the message in the queue. Message Queuing overcomes the lack of signal carrying information, and the pipeline can only
Hosts unformatted byte streams and buffer size constraints.
5. Shared memory: Allows multiple processes to access the same piece of memory space, is the fastest available IPC form. is less efficient for other communication mechanisms
and designed. It is often used in conjunction with other communication mechanisms, such as semaphores, to achieve synchronization and mutual exclusion between processes.
6. Memory mapping (mapped memories): Memory mapping allows any number of interprocess communication, each using the mechanism of the process by putting a shared
The file is mapped to its own process address space to implement it.
7. Semaphore (semaphore): primarily as a means of synchronization between processes and between different threads of the same process.
8. Socket (SOCKET): More general inter-process communication mechanism, can be used for inter-process communication between different machines. Originally the BSD Division of the UNIX system
Developed, but now generally can be ported to other Unix-like systems: both Linux and System V variants support sockets.
18. A single-linked list of head pointers and lead nodes is arranged in reverse order to find the algorithm.
#include
using namespace Std;
typedef struct _node{
int x;
struct _node *pnext;
}node;

#define Len_node (sizeof (NODE))

Node *phead = (node *) malloc (Len_node);

Void Fun (node *p)
{
Node *pcur,//curten node of the old list
*pnewcur;//curten node of new list
Pcur = P head->pnext;
Phead->pnext = NULL;
while (pcur)
{
if (phead->pnext! = NULL)
{//link other node
Pnewcur = Phead->pnext;
Phead ->pnext = Pcur;
Pcur = pcur->pnext;
Phead->pnext->pnext = pnewcur;
}
Else
{//link first node
Phead->pnext = pcur;
Pcur = Pcur->pnext;
Phead->pnext->pnex t = NULL;
}
}
//test print
Pcur = Phead->pnext;
while (pcur)
{
printf ("%d\n", pcur->x);
PC ur = pcur->pnext;
}
}

void Main ()
{
NODE *pcur = Phead;
int i = 10;
while (i--)
{
Pcur->pnext = (NODE *) malloc (Len_node);
Pcur = pcur->pnext;
Pcur->x = i + 1;
}
Pcur->pnext = NULL;
Pcur = phead->pnext;
while (Pcur)
{
printf ("%d\n", pcur->x);
Pcur = pcur->pnext;
}
TEST
Fun (Phead);
}
The 19.C language is about what the static and static functions do.
Static has two meanings: 1 means that the variable is a static storage variable, indicating that the variable is stored in a static store. 2 indicates that the variable is an internal connection, only in this file
Valid internally, other files cannot be applied to the function, and non-static functions are global by default.
What is the difference between a static global variable and a normal global variable: the static global variable is only initialized once, preventing it from being referenced in other file units;
What is the difference between a static local variable and a normal local variable: the static local variable is initialized only once, the next time based on the last result value;
What is the difference between a static function and a normal function: The static function has only one copy in memory, and the normal function maintains a copy of each call.
20. When to use delegate, when to use Notifiction?
Delegate is used for one-to-one, notifiction can be used for one-to-many, pair one or one pairs. You can notify multiple objects.
21. When a constant is declared with a preprocessing # define.
#SECONDS_YEAR (* 365 *) UL
22. Write a proxy signal.
@protocol MyDelegate
-(void) Didjobs: (Nsarray *) args;
@end

@protocol MyDelegate;

@interface Myclass:nsobject
{
ID delegate;
}

This is a proxy I wrote:
@protocol productdelegate<nsobject>
-(void) DoSomething: (Nsinteger) index;
@end

@interface Productviewcontroller:viewcontroller
@property (nonatomic,weak) id<productdelegate> prodelegate;
@end

Call the class implementation interface for this Protocol
Implementation class
[Self dosomething:1];
23. Write an implementation of the NSString class.


Does 24.OC have multiple inheritance? If not, is there a replacement method?
OC inside to achieve multiple inheritance, general use agent.
25.obj-c have a private method? What about private variables?
There are variables and instance variables for the class.
26. What is the meaning of the keyword const? What about the modifier class? The function of static, for the class? and the role of extern c.
The const represents a read-only meaning.
const int A;
int const A;
const int *a;
int * const A;
int const * a const;
The meaning of the first two means that a is a constant integer, and the third indicates that this is a pointer to this long integer number.
The fourth represents a constant pointer to an integer, and the fifth represents a constant pointer to a constant integer number.
27. Why does the standard header file have a structure similar to the following?
#ifndef __incvxworksh
#define __incvxworksh
Prevent the reuse of the chant.
What is the difference between the #import跟 # include @class?
@class declare, just know that there is such a thing, as to what is inside, do not know completely. #import不会出现重复引用的现象.
#include表示引用, duplicate references may occur.
29. What are the differences and connections between threads and processes?
Both the process and the thread are the basic units provided by the operating system, and the system uses the basic unit to implement the concurrency of the system. The main difference is that different
Operating system resource management mode, the process has a separate address space, but the thread does not, a process crashes, in protected mode, the thread will continue to run normally.
A thread is just a different execution path in a process. The thread has its own stack and local variables, but the thread does not have a separate address space, so a
The process also dies when the thread dies. Multi-process programs are more robust than multithreaded programs. But requiring simultaneous execution and sharing of resources can only
Using threads, you cannot use processes.
30. Examples of the synchronization mechanism of several processes, comparative advantages and disadvantages.
1. Ways of communicating between processes:
2. Cause of Process deadlock: loop, mutex, request hold, non-deprivation
3. Deadlock handling: Avoid policy, detect, and unlock deadlocks
31. The difference between heap and stack.
Heap: object, static variable name, class name, loaded when the project is loaded.
Stack: Save the variable name.
32. What is the operation of Kv,key and value.
In OC, the most classic operation is a dictionary, a key corresponding to a value, according to the key to find the object, the key path is a dot to do the key composition of the delimiter
strings, which are used to concatenate the sequence of objects together, the nature of the first key is determined by the previous nature, and through the key path, you can specify any one of the object graphs
The path to the depth that points to the specific properties of the related object.
How 33.C and OC are mixed.
The suffix named. m file identifies the OC file, which is mixed by changing the. m file to a. mm file. However, CPP files cannot be mixed with OC files.
34. What is the automatic release of the pool and how it works.
When you send a autorelease to an object, cocoa puts a reference to the object in the latest auto-release pool, which is a
A legitimate object, so that other objects that automatically release the scope of the pool definition can send a message to him.
When the program executes to the end of the scope, the auto-release pool is automatically freed, and all objects are freed.
Each encounter Copy,retain count will add 1, each encounter release, autorelease count will be reduced by 1.
What are the advantages and disadvantages of 35.OBJC?
Advantages:
dynamic identification;
Indicator calculation;
Elastic information transfer;
is not an overly complex C-derived language;
OC and C + + can be mixed language;
Posing;
Cateogies.
Disadvantages:
namespaces are not supported;
Operator overloading is not supported;
Multiple inheritance is not supported;
Performance is low because many optimization methods are not available.
36.sprintf, strcpy, memcpy when the use of what to pay attention to it?
sprintf
strcpy
memcpy
37. Define a with a variable.
1) shaping a int A;
2) A pointer to the number of integers int *a;
3) A pointer pointer pointing to the number of int** A;
4) An array of 10 shaping numbers int[] A;
The role of the 38.readwrite,readonly,assign,retain,copy,nonatomic property.
property is an attribute access declaration that supports the following properties in parentheses:
1.getting and setting, set method names for setting and getting.
ReadWrite: Readable and writable
ReadOnly: Read-only
Assign: Data,
Retain
Copy: Copying
Nonatomic:
What is the difference between 39.http and socket communication?
http: Is the client with the HTTP protocol request, when sending the request to encapsulate the HTTP request header, and bind the requested data,
The HTTP request is the client unsolicited request, the service side only to the corresponding, once the request is complete, will be disconnected, save resources.
The server cannot actively respond to the client. Unless you have an HTTP long connection, the iphone is primarily using nsurlconnection technology.
Socket: Is the connection between the client and the server using the socket continuation suite word, and there is no requirement to disconnect after the connection, so
A connection channel is maintained between the client and the server, and both parties can proactively send data. Generally in the game or stock development
Use, mainly cfsocketref.
40.TCP and UDP protocol?
TCP: Transmission Control Protocol, which provides reliable, object-oriented network data delivery services. Transmission Control Protocol mainly contains the following
Tasks and Features:
1) Ensure the successful delivery of IP packets.
2) The bulk data sent by the program continues to be encapsulated and reorganized.
3) Ensure that segmented data is correctly sorted and sequentially passed.
4) The integrity of the transmitted data is checked by calculating the checksum.
TCP: Connection-oriented, reliable data flow transmission, data security, slow.
UDP: Non-connection-oriented, unreliable data flow delivery, fast.
41. Other models?
Singleton mode, Agent mode, Factory mode.
42. What is push?
Push is the client program left the backdoor port, the client is always listening to the back door to the request, so the server can actively to this port
Push messages.
43. Static link library?
For. A files, different projects inside the import file can be used inside the class.
44. What is a sandbox model? What actions are private API categories?
Sandbox model:
Inside the iphone sandbox model, there are four folders: Documents, TMP, app, Library. The manually saved files are saved in documents.
1.Documents: You should write all of your application data files into this folder, which is mostly stored for data or other things that should be backed up.
2.app: This is the application's package directory, which contains the application itself. Since the application must be signed, all you cannot do at run time
Work with this folder. Otherwise the program will not function properly.
3.library:cache and preferences two folders, cache folder: For application-specific support files, save the application
The information needed to start again.
Preferences: Contains the application's preferences file, you should not directly create a preference file, but should use Nsuserdefault to obtain
and set the application preferences.
Get the Sandbox home directory:
nsstring* HomePath = Nshomedirectory ();
4. Get the path to the resource file in the application package:
nsstring* ImagePath = [[NSBundle mainbundle] pathforresource:@ "apple" oftype:@ "PNG"];
uiimage* iamge = [[UIImage alloc] initwithcontentsoffile:imagepath];
45. File IO Write:
1. Write the data to the documents directory:
-(BOOL) Writeapplicationdata: (NSData *) data tofile: (NSString *) FileName {
Nsarray *paths = Nssearchpathfordirectoriesindomains (NSDocumentDirectory, Nsuserdomainmask, YES);
NSString *docdir = [Paths objectatindex:0];
if (!docdir) {
NSLog (@ "Documents directory not found!"); return NO;
}
NSString *filepath = [Docdir stringbyappendingpathcomponent:filename];
return [data Writetofile:filepath Atomically:yes];
}

2. Read data from the documents directory:
-(NSData *) Applicationdatafromfile: (NSString *) FileName {
Nsarray *paths = Nssearchpathfordirectoriesindomains (NSDocumentDirectory, Nsuserdomainmask, YES);
NSString *docdir = [Paths objectatindex:0];
NSString *filepath = [Docdir stringbyappendingpathcomponent:filename];
NSData *data = [[[NSData alloc] initwithcontentsoffile:filepath] autorelease];
return data;
}
Nssearchpathfordirectoriesindomains The main thing is to return an absolute path for storing the files we need to store.
-(NSString *) DataFilePath {
Nsarray *paths = Nssearchpathfordirectoriesindomains (NSDocumentDirectory, Nsuserdomainmask, YES);
NSString *documentsdirectory = [Paths objectatindex:0];
return [documentsdirectory stringbyappendingpathcomponent:@ "Shoppingcar.plist"];
}
nsfilemanager* Fm=[nsfilemanager Defaultmanager];
if (![ FM fileexistsatpath:[self DataFilePath]) {

The following is a save on the path to the file development
[FM createdirectoryatpath:[self DataFilePath] Withintermediatedirectories:yes attributes:nil Error:nil];
Get all the filenames in a directory
Nsarray *files = [FM subpathsatpath: [self datafilepath]];
Read a file
NSData *data = [FM contentsatpath:[self DataFilePath];
Or
NSData *data = [NSData datawithcontentofpath:[self DataFilePath];
}
46. What data storage methods are used?
Core data, Sqllite, object serialization, file direct read and write, Nsuserdefault.
The file is read directly to >core data> object serialization >sqllite>nsuserdefault.
47. What are the common methods of threading? How do you deal with multithreading? Multi-threaded questions do you understand?
Threads are created in several ways, thread locking, Hibernate, Wake, unlock, exit.
Multithreading to consider the problem of synchronization, solve the synchronization problem is to lock a resource, when a thread
Other threads do not work while the resource is being manipulated.
The system comes with the function of thread pool:
You can use nsoperationqueue wherever you need to start multiple threads, and objects that are added to Nsoperationqueue need to inherit nsoperation.
Nsoperationqueue will launch a separate thread inside the system to execute the main method that is added to the object.
The common place is to download pictures and files with Nsoperationqueue. If it's a thread pool that you create, it's just the time to start multiple threads
Object into a large array, and if you need to start multiple threads, use the idle thread from the array first. Manage the thread pool yourself
The biggest problem is that it is not good to handle the callback of the threading method when multiple threads are started, when the user jumps across multiple interfaces.
What is the difference between 48.init and initwithobject?
The object created by Init does not have the auto-release feature.
49. Have you used JSON parsing? What's the bottom of them?
The underlying principle is to iterate through the characters in the middle of the string, and ultimately according to the formatting of special characters, such as: {},[],:. Be differentiated. The {} number is the beginning of a dictionary,
[] is the beginning of a data: the watershed of the key value, and ultimately the conversion of JSON into a dictionary. Dictionaries may be dictionaries, data, strings.
50. How do you connect to the server? What if a network outage is in the request?
After the nsurlconnection is connected, there is a system delegate method to process the server's data, and if the network connection fails, the corresponding method is called.
What is the principle of 51.xml parsing?
Nsxmlparser, the other parsing method is a custom binary parsing, is to parse by byte, telephone conversation is such a paper, you can also use
A special symbol is used to concatenate data between strings using special symbols, which can be segmented into the data used.
52. What is the role of the category?
1. The method that would otherwise be required to be declared in. h is declared in the. m file, which is achieved by making the method non-public.
2. It is easy to extend the class, even the system classes can be easily extended to maintain the original structure of the code is not affected.
3. Categories can be written into different. h or. m files, which can be easily viewed by spreading the code to a place where the extended functionality of the category is to be associated.
53. What is the method for splitting the thread back to the main thread?
[Self Performselectoronmainthread: @selector (BUTTONGO2) Withobject:nil] waituntildone:yes];
[Self performselector: @selector (BUTTONGO2) onthread:[nsthread Mainthread] Withobject:nil Waituntildone:yes];
54. How do you perform memory leak detection when you are developing a large project?
XOCDE There is a tool inside, run-->start with performance tool inside there is a instruments under a leaks tools, start this
Tool, run the project, the tool can show the memory leaks, double-click to find the source of the location, can help with the memory leak problem.
How is the value passed between 55.view and view?
Agent.
56. What are the methods for moving an object from one point of the interface to another?
Animation.
57. What encryption methods do you know?
MD5, ASE
58. Map positioning?
I never did.
59. Open the URL.
[[Uiapplcation shareapplication] Openurl:[nsurl urlwithstring:]];
60.http network communication.
ASIHTTPRequest is an open source project directly on Cfnetwork: Direct submission (HTTP POST) file API, asynchronous request, automatic management of uploads and downloads of queues
Management machine, Asiformdatarequest used for uploading files, picture data.
61. Image browsing.
Select a picture from the camera, Uiimagepickercontroller.
62. Serialization of objects.
Nscoding Encodewithcoder Initwithcoder
Nskeyedunarchiver Nskeyedarchiver
63. Various Picker
Uidatapicker and Uipickerview.
64. Movie playback, audio playback.

65. Threads?
Rules for creating and using threads.
Nsthread
Three different ways:
-(ID) init;
-(ID) Initwithtarget: (ID) Target selector: (SEL) Selector object: (ID) argument;

Thread Lock:
Nscondition Method:
[Thread lock] lock [thread singnal] thread start [thread unlock] unlock [thread exit] line threads unlocked
Sleep (n);
66. Various sorting algorithms?

67. Communication underlying principle.
Answer: OSI seven layer model
7 Application layer: FTP,SMTP,HTTP,TELNET,TFTP (through various protocols, eventually packaged into TCP packets, sent to the network!) )
6 Presentation layer:
5 Session Layer:
4 Transport layer: TCP UDP
3 Network layer: IP,ICMP,IGRP,EIGRP,OSPF,ARP
2 Data Link layer: STP,VT
1 Physical Layer:
68. Why are the delegate properties of many built-in classes such as Uitableviewcontroller assign rather than retain?
can cause circular references
All reference counting systems have problems with cyclic applications. For example, the following reference relationship:
* Object A was created and referenced to object B.
* Object B was created and referenced to object C.
* Object C was created and referenced to object B.

At this time, the reference counts for B and C are 2 and 1, respectively.
When a no longer uses B, the call release releases the ownership of B, because C also references B, so the reference count for B is 1,b and will not be freed.
B is not released, the reference count of C is 1,c and will not be released. From then on, B and C remain in memory forever.
In this case, the circular reference must be interrupted and the reference relationship maintained through other rules. Our common delegate is often the property of the assign way, not the retain way,
The assignment does not increase the reference count, which is to prevent unnecessary circular references being generated on both sides of the delegation.
If a Uitableviewcontroller object a acquires ownership of UITableView object B through retain, the delegate of this UITableView object B is a,
If this delegate is retain way, there is basically no chance of releasing the two objects. You should also be aware of this when designing your delegate model.
69. What is the retain count for the person object after each of the following lines of code is executed?
Person *person = [[Person alloc] init]; Count 1
[Person retain]; Retain Count 2
[Person Release];retain Count 1
[Person Release];retain count = 0
71.main ()
{
int a[5]={1,2,3,4,5};
int *ptr= (int *) (&a+1);
printf ("%d,%d", * (a+1), * (ptr-1));
}

Answer: 2,5

* (a+1) is a[1],* (ptr-1) is a[4], the result of the implementation is 2,5
&a+1 is not the first address +1, the system will assume that the offset of an array of a, is offset by the size of an array (this example is 5 int)
int *ptr= (int *) (&a+1);
Then PTR is actually & (a[5]), i.e. a+5
The reasons are as follows:
&a is an array pointer whose type is int (*) [5];
and the pointer plus 1 to add a certain value according to the pointer type, different types of pointer +1 after the increase in size.
A is an int array pointer of length 5, so add 5*sizeof (int)
So ptr is actually a[5]
However, PRT is not the same as (&a+1) type (this is important)
So prt-1 will only subtract sizeof (int*)

A,&a's address is the same, but it doesn't mean the same thing.
A is the address of the first address of the array, which is a[0], &a is the first address of the object (array),
A+1 is the address of the next element of the array, that is, a[1],&a+1 is the address of the next object, or A[5].
72.sprintf, strcpy, memcpy when the use of what to pay attention to it?
These functions differ in the ability to implement functions and manipulate objects, and the strcpy function operates on strings that complete the function of the source string to the target string.
The SNPRINTF function Action object is not limited to strings, although the target object is a string, but the source object can be a string, or it can be any basic
Type of data. This function is used to implement a conversion function (string or basic data type) to a string. If the meta-object is a string, and
Specify the%s format character, or you can implement a string copy.
memcpy is a memory copy that allows the contents of one block of memory to be copied into another memory block.
strcpy is undoubtedly the most suitable choice: high efficiency and easy to invoke.
snprintf to specify format characters and convert them in a format that is cumbersome and inefficient.
memcpy is efficient, but requires additional copies of the memory length of this parameter, error-prone and inconvenient to use, and if the length specified too large
(The optimal length is the source string length + 1), which also leads to degraded performance. In fact, the strcpy function is generally called inside the memcpy function or
The assembly is implemented directly to achieve efficient purposes. Therefore, there should be no significant difference in performance between using memcpy and strcpy copy strings.
For non-string types of data replication, strcpy and sprintf are generally powerless, but memcpy can. Memcpy's strength is to
A copy of a structure or an array is implemented (usually internally), with the purpose of being either efficient, convenient, or even both.
void *memcpy (void *dest, const void *SRC, size_t n);
Copies n bytes from the starting position of the memory address referred to by the source SRC to the starting position of the memory address referred to by the target dest.
Prototype declaration: Char *strcpy (char* dest, const char *SRC);
Description: The memory areas referred to by SRC and dest cannot overlap and dest must have sufficient space to accommodate the SRC string.
Returns a pointer to the dest.
int sprintf (char *buffer, const char *format, [argument] ...);

73. Write an implementation of the NSString class.
+ (ID) initwithcstring: (const char *) nullterminatedcstring encoding: (nsstringencoding) encoding;
+ (ID) stringwithcstring: (const char*) nullterminatedcstring
Encoding: (nsstringencoding) encoding
{
NSString *obj;
obj = [self allocwithzone:nsdefaultmalloczone ()];
obj = [obj initwithcstring:nullterminatedcstring encoding:encoding];
return autorelease (obj);
}

For the interview needs, only the work of reference, I wrote, if there is wrong place, welcome to point out.

Questions for iOS base plane

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.