Ios static library usage

Source: Internet
Author: User

Ios static library usage
Ios static library usage 3906 people read comments (0) collect reports

The static library file for ios is *. a. If you need to use it, you can use A simple method that I learned today. To put it simply, if there is A mobile project a and A static library Project B, A wants to use B. a. follow these steps:

1. Drag project A into Project B. Under product B, the red B. a is displayed, indicating that it has not been compiled (add the. m file you want to export in the project settings ).

2. Select the object to be compiled. A simulator under B or a real machine under B is compiled. (The static library generated on the simulator and those generated on the real machine cannot be mixed)

3. Create A folder (new group) in A and drag it into the header file that needs to be imported in B.

4. Add the compiled. A static library to the framework of a, and the compiled library will not be red.

5. Where necessary # import the required header file. OK!

 

The following two articles show how to generate and use static databases written by others. There are also resource binding methods available for reference!

I. IOS development-generate a static library (.)

 

Due to the extreme lack of iPhone controls and restrictions on the reuse of custom components, we have accumulated a large number of "pure code" components in past projects-due to the limitations of IB itself, we cannot encapsulate these components into an IB Component Library (we originally wanted to reuse these components by distributing xib files, but ultimately it was impossible, apple's Plug-in programming does not support iPhone ).

Finally, we thought of static databases. Although this is still a primitive method of reuse, we can at least hide the source code of the component.

Next, we use the iPhone static library to further encapsulate the custom component CheckButton. (For component implementation, refer to the previous blog "Implementation of custom control check boxes and single keys")

1. Implement static databases

Create a project and select "Cocoa Touch Static Library" under the Library ". Name the project, for example, yhyLibrary.

Copy the four source files of the CheckButton component: CheckButton. h. CheckButton. m, RadioGroup. h. RadioGroup. m to the Classes directory, and copy the four resource files of the CheckButton: check.png?uncheck.png=radio.png=unradio.png to the project folder.

Press? + B compilation. a. a file is generated under the Products directory.

Ii. Create a resource bundle

Objects are not added to the target. That is to say, the compilation result does not contain these resources. Therefore, if a static library is called at this time, all resources (strings and images) are missing.

We can build resources into a separate Bundle ).

Create a project named "Mac OS X-> Framework & Library-> Bundle": yhyLibraryBundle.

Then copy 4. PNG files to Resouces. Compile and generate the yhyLibraryBundle. bundle file.

Return to the static library project and create a class: Utils.

Edit Utils. h:

# Define MYBUNDLE_NAME @ "yhyLibraryBundle. bundle"

# Define MYBUNDLE_PATH [[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent: MYBUNDLE_NAME]

# Define MYBUNDLE [NSBundle bundleWithPath: MYBUNDLE_PATH]

NSString * getMyBundlePath (NSString * filename );

Edit Utils. m:

# Import "Utils. h"

NSString * getMyBundlePath (NSString * filename)

{

NSBundle * libBundle = MYBUNDLE;

If (libBundle & filename ){

NSString * s = [[libBundle resourcePath] stringByAppendingPathComponent: filename];

NSLog (@ "% @", s );

Return s;

}

Return nil;

}

The getMyBundlePath function can obtain the absolute file path of a specific resource in the bundle yhyLibraryBundle, for example:

/Users/kmyhy/Library/Application Support/iPhone Simulator/4.2/Applications/libraries/yhyLibTest. app/yhyLibraryBundle. bundle/Contents/Resources/radio.png

Modify the code in CheckButton. m, import the Utils. h header file, and change the image retrieval code from imageNamed to imageWithContentsOfFile, for example:

[Icon setImage: [UIImage imageWithContentsOfFile: getMyBundlePath (checkname)];

That is, the image resource is read through the absolute path.

In addition to this method, we can also simply copy four resource files to the application project that calls the static library (without modifying the static library code ).

 

Iii. Static Library call

1. Add a static library

Create a Window-based Application project and name the project, such as yhyLibraryTest.

Right-click Frameworks-> Add-> Existing Files... and Add the yhyLibrary. xcodeproj file of the static library project to the current project (do not select Copy items ).

 

Select the added yhyLibrary. xcodeproj file and check the "include to target" option. For example, set the last check box:

 

2. Add Direct Dependencies (that is, reference the project)

Similar to the reference project in Visual Studio, the purpose is to directly edit the referenced static library project in this project, so as to modify the static library.

Select "FirstLibraryTest" under the "Targets" directory and click "info" to bring up the target property window and switch to the "General" column, click the "+" button under "Direct Dependencies" to add the static project library libyhyLibrary to Direct Dependencies. The result is as follows:

 

 

3. Add a header file search path

Open the project info window, find the Header Search Paths in the Build column, and add the string "../yhyLibrary ".

4. Reference a resource bundle

Right-click Copy Bundle Resources of target and choose Add-> Existing File ...", Add the yhyLibraryBundle. bundle generated earlier to the project.

5. Call classes in the static library

Edit application :( UIApplication *) application didfinishlaunchingwitexceptions: code in the method:

// Single-choice button group

RadioGroup * rg = [[RadioGroup alloc] init];

// 1st radio buttons

CheckButton * cb = [[CheckButton alloc] initWithFrame: CGRectMake (20, 60,260, 32)];

// Add the single-choice button to the button group

[Rg add: cb];

Cb. label. text = @"★";

Cb. value = [[NSNumber alloc] initWithInt: 1];

// Set the button as a single-choice button style

Cb. style = CheckButtonStyleRadio;

// Add View

[Self. window addSubview: cb];

[Cb release]; // after adding, it is automatically held and can be released

// 2nd radio buttons

Cb = [[CheckButton alloc] initWithFrame: CGRectMake (20,100,260, 32)];

[Rg add: cb];

Cb. label. text = @"★★";

Cb. value = [[NSNumber alloc] initWithInt: 2];

Cb. style = CheckButtonStyleRadio;

[Self. window addSubview: cb];

[Cb release];

// 3rd radio buttons

Cb = [[CheckButton alloc] initWithFrame: CGRectMake (20,140,260, 32)];

[Rg add: cb];

Cb. label. text = @"★★★";

Cb. value = [[NSNumber alloc] initWithInt: 3];

Cb. style = CheckButtonStyleRadio;

[Self. window addSubview: cb];

[Cb release];

The running result is as follows:

 

6. Distribution of static databases

Package the generated. a and. bundle files and distribute them to others.


2. Use static link library (Xcode4.6.2)

 

I. theoretical part

 

In the actual programming process, some common functions are usually made into function libraries for use by other programs. One is to reuse the code, and the other is to keep the core technology confidential. Therefore, in actual project development, function libraries are often used. The function libraries are divided into static and dynamic libraries. Similar to the dynamic and static languages that most people are familiar with, static and dynamic languages are called relative to the compilation and runtime periods: static libraries are linked to the target code during program compilation, when the program is running, you no longer need to change the static library. When the program is compiled, the dynamic library is not linked to the target code. It is loaded only when the program is running, because the dynamic library is also required during the running of the program.

 

The static Link Library applies:

1. You want to package some codes that will not be modified in the future for other projects.

2. You want to encapsulate part of the code for use by others, and do not want others to see your implementation method.

 

Ii. Practice

 

How to Create a static link library (lib ):

1. For a new project. When creating a project, select Framework & Library-> cocoa touch static library to directly create a static Link Library Project. By default, there are two projects with the same name. h and. m: continue to add files. m will be automatically added to Build Phases-> Compile Source, indicating that the Code will be compiled into lib. You can delete the code that you do not want to be compiled.

2. If you want to extract a lib from a project, add target and select Framework & Library-> cocoa touch static library. There will be one more folder in xcode navigator, with the same name as your new target. Similarly, you can add the files you want to add to lib in Build Phases-> Compile Source.

 

Next: create two single view template projects DemoOne and DemoTwo. Among them, I want to use DemoTwo as a static library and then use it in DemoOne:


A. Open DemoTwo.

Mouse selection:

Click Add Target and choose Framework & Library-> Cocoa Touch Static Library-> Create a Library named MyLib:

 

Specifically, the target MyLib is the library we want to provide externally. The interface provided externally by this library can be controlled by ourselves. Of course, multiple targets can be added, each target static library can provide different interfaces. Here I only use a static library MyLib. The default target DemoTwo function of MyLib is similar to that of DemoTwo when DemoTwo is created. Therefore, you must add Frameworks to MyLib:

 

Then, write the MyLib library to provide external functions. In the DemoTwo project, create a group named LibMethod, and create three new classes: Func1, Funk2, and UILabelEX, the implementation code is very simple, just print the log.

Func1 is similar to Func2. Take Func1 as an example:

 

@ Interface Func1: NSObject

-(Void) func1Log;

@ End

# Import "Func1.h"

@ Implementation Func1

-(Void) func1Log {

NSLog (@ "Func1 log ");

}

@ End

 

UILabelEX is a class extension, because it was previously said that class extensions cannot be placed in static libraries, so try it yourself:

 

# Import

@ Interface UILabel (TestColor)

-(Void) testMethodColor;

@ End

# Import "UILabelEX. h"

@ Implementation UILabel (TestColor)

-(Void) testMethodColor {

NSLog (@ "testMethodColor ");

}

@ End

 

Make sure that the Compile Sources of MyLib contains the class we just created. m file, because what is added here. the m file is equivalent to the interface provided by the MyLib static library. If it is not added, click + to add it manually:

 

Close the DemoTwo project, open the DemoOne project, open the DemoTwo project folder, and drag DemoTwo. xcodeproj to DemoOne:

 

Then add the database to DemoOne and select the MyLib we created in DemoTwo:

 

If libMyLib. a is red, DemoTwo is not compiled to generate libMyLib. a. Don't panic. This is a small thing:

 

Theory (before compilation, select build configuration in the scheme of target, select the simulator, and then compile.

 

Note: The lib compiled in device mode can only run on a real machine, and the lib compiled in simulator mode can only be used for simulator debugging. Then find and compile the lib, and copy it to the project that requires it.

If you want a lib to run on both the simulator and the real machine, compile it once and find both lib libraries, use the command to merge the two lib into one. The command is: lipo-create sim. a dev. a-ouput libXX. libXX. a can be used.

Add the lib and header files to be referenced in the new project to the new project .)

 

I will use the simulator as an example to compile and generate lib for DemoTwo.

 

There is a detailed problem, that is, whether the lib you generated is used on a real machine or a simulator? It's easy. First select Mylib, and then click Edit Scheme in the response. You can choose whether it is a simulator or a real machine at the top, and then build it:

 

In DemoOne, the dependent database is normal:

 

Then let DemoOne use the excuse provided by DemoTwo:

First, DemoOne should introduce the DemoTwo interface in DemoOne, DemoOne should create a group, name lib, and put the interface in DemoTwo. the H file is dragged to the lib folder as a reference (if the file is not referenced, the interface file in DemoTwo will not change as the interface code in DemoTwo changes ):

 

At this point, the work is basically completed, and then the following code is implemented in the ViewController of DemoOne:

 

# Import "ViewController. h"

# Import "Func1.h"

# Import "Func2.h"

@ Implementation ViewController

-(Void) viewDidLoad

{

[SuperviewDidLoad];

Func1 * obj1 = [[Func1alloc] init];

[Obj1 func1Log];

 

Func2 * obj2 = [[Func2alloc] init];

[Obj2 func2Log];

}

@ End

Compilation and running are not unexpected. log printing should be performed, which indicates that we have basically succeeded.

 

But is it missing? The # import "UILabelEX. h" class has not been used yet. This class is an extension of the UILabel type:

 

# Import

@ Interface UILabel (TestColor)

-(Void) testMethodColor;

@ End

# Import "UILabelEX. h"

@ Implementation UILabel (TestColor)

-(Void) testMethodColor {

NSLog (@ "testMethodColor ");

}

@ End

Use the following code:

 

UILabel * obj3 = [[UILabel alloc] init];

[Obj3 testMethodColor];

Then compile and run the program. The cause is:

-[UILabel testMethodColor]: Unrecognized selector sent to instance 0x7574190

 

Clearly in the code UILabel can find testMethodColor, but actually did not find this method, this place has a detail, the answer here: http://developer.apple.com/library/mac/#qa/qa1490/_index.html

 

In DemoOne's build setting, search for Other Linker Flags, find the settings, add a parameter-ObjC to it, and then compile and run it. It seems that everything is OK.

 

 

Others:

1. if you do not follow the steps, the following error may occur. This problem may occur in projects using simulators:

 

  1. Undefined symbols for architecture i386:
  2. "_ OBJC_CLASS _ $ _ RequestServer", referenced from:
  3. Objc-class-ref in ListViewController. o
  4. Objc-class-ref in SettingsViewController. o
  5. Ld: symbol (s) not found for architecture i386
  6. Clang: error: linker command failed with exit code 1 (use-v to see invocation) Don't worry. Go to DemoTwo's lib and add the. m file of the external interface to it:

     

     

    2. If the lib used by the real machine is used, you may encounter an error related to arm7. I have not encountered it yet. The following is a reference solution (I have not tried it myself ):

     

    Static libraries in Xcode4.5.2 and iOS6 applications do not support armv7s Solutions

     

    Error details:
    Ld: file is universal (3 slices) but does not contain a (n) armv7s slice:/zhangyg/XXX/libs/libxxx. a for architecture armv7s

    Clang: error: linker command failed with exit code 1 (use-v to see invocation)


    The solution is as follows:

     

     

    Method 1: Set BuildActiveArchitectureOnly value is set to Yes

    Method 2: Set ValidRemove armv7s from ubuntures
    Method 3: If the source code of libxxx. a is available, compile a version of armv7s of libxxx. a, and merge it into libxxx..

     

    3. The simulator runs normally, but the following error is printed in the case of crash:

    Dyld: lazy symbol binding failed: Symbol not found: _ objc_setProperty_atomic_copy
    Referenced from:/var/mobile/Applications/DFCB17A5-52AC-41CD-9ECB-94415C7D36F3/kalagame-demo.app/kalagame-demo
    Expected in:/usr/lib/libobjc. A. dylib


    Dyld: Symbol not found: _ objc_setProperty_atomic_copy
    Referenced from:/var/mobile/Applications/DFCB17A5-52AC-41CD-9ECB-94415C7D36F3/kalagame-demo.app/kalagame-demo
    Expected in:/usr/lib/libobjc. A. dylib

    Solution:

     

    This error indicates that the App executable file references the functions objc_setProperty_nonatomic or objc_setProperty_atomic. However, the two functions are obviously not directly called in the Code and should be generated by the system during compilation. After debugging, it is found that this error always occurs when setting the attributes of an object. The class of this object is defined in the static library, so I looked at the static library.
    After investigation, we found that the cause of this problem was that the Deployment Target of the static library was set to 6.0. Because struct and objc_setProperty_atomic are newly added functions in iOS6, if the Deployment Target of the static library is set to iOS6, the new APIs objc_setProperty_nonatomic and objc_setProperty_atomic will be used after compilation. Because iOS5 does not have these APIs, it will crash after running.

    Conclusion
    During static library compilation, the Deployment Target must be lower than or equal to the Deployment Target of the project. Otherwise, it is prone to incompatibility between earlier iOS versions.


     

    4. Suddenly, the Project Name of the static library project needs to be changed, so the right-hand static library project executable File (the blue-colored one) is selected, and Show File Inspector is selected in the pop-up menu, the "XIB Attribute Modification entry" pops up. You can modify the project name. However, after modifying the project name, several interfaces provided by the static library become invalid.

    Error: Undefined symbols for architecture armv7:

    Solution: In the project settings for referencing the static library, re-Add the static library file, which is the XXX. a file.

Related Article

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.