We are here to obj-c Programming 01 Medium Box With a little change , One is the automatic synthesis accessor added , Second, we will Box According to its standard writing, it can be divided into 3 File , The header file Box.h, Class implementation file Box.m, And the master file test.m.

1.Box.h

#import <Foundation/Foundation.h>
@interface Box:NSObject{
int l;
int w;
}
@property int l,w;
-(void)print;
@end

2.Box.m

#import "Box.h"
@implementation Box
@synthesize l,w;
-(void)print{
NSLog(@"l=%d,w=%d",l,w);
}
@end

3.test.m

#import "Box.h"
int main(int argc,char **argv)
{
@autoreleasepool {
NSLog(@"hello class! :)");
Box *box = [[Box alloc] init];
[box setL:100];
[box setW:200];
NSLog(@"look box :");
[box print];
NSLog(@"other way to look box : l=%d,w=%d",[box l],[box w]);
}
return 0;
}

The compilation command and execution result are :

wisy@wisy-ThinkPad-X61:~/src/objc_src/class_std$ clang -O3 -g0 -MMD -MP -DGNUSTEP -DGNUSTEP_BASE_LIBRARY=1 -DGNU_GUI_LIBRARY=1 -DGNU_RUNTIME=1 -DGNUSTEP_BASE_LIBRARY=1 -fno-strict-aliasing -fexceptions -fobjc-exceptions -D_NATIVE_OBJC_EXCEPTIONS -pthread -fPIC -Wall -DGSWARN -DGSDIAGNOSE -Wno-import -g -O2 -fgnu-runtime -fconstant-string-class=NSConstantString -I. -I/home/wisy/GNUstep/Library/Headers -I/usr/local/include/GNUstep -I/usr/include/GNUstep -lobjc -lgnustep-base -o cls_test Box.m test.m
wisy@wisy-ThinkPad-X61:~/src/objc_src/class_std$ ./cls_test2014-06-28 13:53:35.666 cls_test[16916] hello class! :)
2014-06-28 13:53:35.668 cls_test[16916] look box :
2014-06-28 13:53:35.668 cls_test[16916] l=100,w=200
2014-06-28 13:53:35.668 cls_test[16916] other way look box : l=100,w=200

I started in @interface There is no definition of instance variables in , As a result, the compiler reported an error :

Box.m:4:14: error: synthesized property 'l' must either be named the same as a
compatible instance variable or must explicitly name an instance variable
@synthesize l,w;
^
Box.m:4:16: error: synthesized property 'w' must either be named the same as a
compatible instance variable or must explicitly name an instance variable
@synthesize l,w;

After adding it, it will be normal , Unknown cause ( The book says it can't be added ). In addition, it should be noted that the writing method of automatic synthesis is SetL and SetW, Don't get me wrong .

We can also abbreviate the read-write synthesizer method , Even the general method is as follows :

#import "Box.h"
int main(int argc,char **argv)
{
@autoreleasepool {
NSLog(@"hello class! :)");
Box *box = [[Box alloc] init];
[box setL:100];
[box setW:200];
box.l = 101; //same as [box setL:101]
box.w = 102; //same as [box setW:102]
NSLog(@"look box :");
[box print];
(void)box.print; //same as [box print]
NSLog(@"other way to look box : l=%d,w=%d",[box l],[box w]);
NSLog(@"other way to look box : l=%d,w=%d",box.l,box.w); //same as [box l],[box w]
}
return 0;
}

The first 17 The line is preceded by (void) Tell the compiler I don't care print There's no return , If not, there will be a warning :

test.m:17:3: warning: property access result unused - getters should not be
used for side effects [-Wunused-value]
box.print;
^~~~~~~~~

In principle, general methods are not called in this way , It's a normal one [ ] That's right .

[2014.07.03 The first 1 Add content for the first time ]: The atomic keyword of the attribute

We can often see the following writing in the source code :

@property(nonatomic,copy)Some_class *obj;

among copy The key words can be in the following section 11,12 The answer to this question is , Let's talk about the former . Use here nonatomic To tell the system not to use mutex (mutex) Lock to protect access methods to properties , This will be used in writing single threaded code . If you are in multithreading and need synchronization security , You can't specify nonatomic Or you can specify atomic( The default value is ) keyword , At this time, the system can automatically add mutex code to ensure the safety of multithreading synchronization .

[2014.07.05 The first 1 Time modification ]:nonatomic The expansion of features

In the use of nonatiomic How does the feature code actually unfold ? as follows :

{

[threadLock lock];

//use val

[threadLock unlock];

}

[2014.07.05 The first 2 Add content for the first time ]: Properties and extensions of synchronous Syntax

There are other variants of the properties and synchronization syntax introduced earlier , We can define only reader methods or writer methods when declaring properties , You can also change the name of the reader or writer's method ; In the later synchronization , We can also change the instance variables bound to properties :

Here's the code , I believe it's clear at a glance :

#import<Foundation/Foundation.h>
#define msg(...) NSLog(__VA_ARGS__)
@interface Foo:NSObject{
int _idx;
NSString *_name;
}
@property (getter=idx_r,setter=idx_w:) int idx;
@property (retain)NSString *name;
-(NSString*)description;
@end
@implementation Foo
@synthesize idx=_idx,name=_name;
-(NSString*)description{
return [NSString stringWithFormat:@"_idx:%d,idx:%d,_name:%@,name:%@",\
_idx,self.idx,_name,self.name];
}
@end
int main(int argc, char *argv[]){
@autoreleasepool {
Foo *foo = [[Foo alloc] init];
[foo idx_w:101];
[foo setName:@"helo foo!"];
msg(@"%d %@ %@",[foo idx_r],[foo name],foo.name);
msg(@"%@",foo);
}
return 0;
}

The results of compiling and running are as follows :

wisy@wisy-ThinkPad-X61:~/src/objc_src$ clang -objc-arc -O3 -g0 $OBJC_OPTS -lobjc -lgnustep-base -o
1 1.m
wisy@wisy-ThinkPad-X61:~/src/objc_src$ ./1
2014-07-05 10:36:46.143 1[3576] 101 helo foo! helo foo!
2014-07-05 10:36:46.146 1[3576] _idx:101,idx:101,_name:helo foo!,name:helo foo!

Actually sum @synthesize similar , There is also a synchronous keyword @dynamic, The access method generated by this keyword should be written manually , In this way, you will have more freedom to access methods !

obj-c Programming 02: More articles on automatic composition of access methods for classes

  1. Python Programming - Object oriented and class oriented

    One . Object oriented programming 1. Process oriented VS object-oriented (1) Programming paradigm Programming is when a programmer uses a specific syntax + data structure + Algorithmic code that tells a computer how to perform a task , A program is a group of programs written by a programmer to get the result of a task ...

  2. [.net Fundamentals of object-oriented programming ] (9) Classes and instances of classes

    [.net  Fundamentals of object-oriented programming ] (9)  Classes and instances of classes class  , As the name suggests, it is classification . Category means . We want object-oriented programming , We need to classify different things . Class can be said to be .net The core of object-oriented . class : It has the same attributes and work ...

  3. Programming to realize Windows The system logs in automatically

    Programming to realize Windows The system logs in automatically principle : Through the registry modification to achieve .Windows Built in automatic login mechanism , When logging into the system ,winlogon Will check the registry has not set automatic login , If it is set, the user name and password will be read , ...

  4. PHP Design patterns : Class automatically loads 、PSR-0 standard 、 Chain operation 、11 Object oriented design pattern implementation and use 、OOP The basic principles and auto loading configuration of

    One . Class automatically loads SPL function (standard php librarys) Class automatically loads , Even though  __autoload()  Functions can also automatically load classes and interfaces , But it is more recommended to use  spl_autoload_registe ...

  5. 《 Challenge 30 God C++ Entry limit 》C++ Introduction to object oriented programming : class (class)

        C++ Introduction to object oriented programming : class (class) In the last two articles, we focused on the operation of knowledge about structure . In the future, we will gradually focus on c++ As a subject , This also means that our tutorial has officially entered object-oriented programming . In the previous tutorial, I ...

  6. Concurrent programming --Concurrent- Introduction to tools

    Concurrent programming --Concurrent- Introduction to tools Concurrent programming --Concurrent- Introduction to tools CountDownLatch CylicBarrier Semaphore Condition Object monitor ...

  7. python Concurrent programming 02 / Multi process 、 Process creation 、 process PID、join Method 、 Process object properties 、 Daemon

    python Concurrent programming 02 / Multi process . Process creation . process PID.join Method . Process object properties . Daemon Catalog python Concurrent programming 02 / Multi process . Process creation . process PID.join Method . Process object properties . Daemon ...

  8. Java Concurrent programming :Thread The use of the class

    Java Concurrent programming :Thread The use of the class in front 2 This article talks about the origin of thread and process respectively . And how to Java How to create threads and processes in . Today, let's learn about Thread class , I'm learning Thread Before class , Let's start with thread related knowledge ...

  9. [.net Fundamentals of object-oriented programming ] (10) Class members ( Field 、 attribute 、 Method )

    [.net  Fundamentals of object-oriented programming ] (10)  Class members ( Field . attribute . Method ) Previously defined Person Class , The members include : Field . attribute . Method . Events, etc. , Besides , The nested class mentioned above is also a member of the class . a. Class members are divided into : static state ...

Random recommendation

  1. 【ORACLE】 special NULL

    NULL Is a unique data type in the database Oracle The description of space in nullAbsence of a value in a column of a row. Nulls indicate missing, ...

  2. JavaScript Flow of events

    What is? JS Flow of events In the early IE The event spread from top to bottom , From document Step by step down to the target element : and Netscape The company's Netscape Navigator It's going in the opposite direction , That is, starting with the target element ...

  3. Linux/Unix shell Scripts monitor disk free space

    Linux Monitor the free space of the disk shell Script , For system administrators or DBA Come on , essential . Here's a monitoring disk space shell Sample scripts , For your reference . 1. Monitor disk free space shell Script robi ...

  4. NSIS Learning notes ( turn )

    from :http://blog.csdn.net/lee353086/article/details/45919901 NSIS Learning notes Date:2015-05-20Author:kagulaEnv:V ...

  5. SEO Front end optimization

    Reduced code Remove some redundant code from the web page , There are such tools on the Internet , It can help to complete , If necessary , We can take the comments out of the code , Even empty lines and the like are removed , Minimize the amount of code , To reduce the size of the page . CSS Sprites Popular point ...

  6. View the real time public network ip

    icanhazip.com Let you know your public network anywhere IP Address icanhazip.com Let you know your public network anywhere IP Address icanhazip.com Let you know your public network anywhere IP Address ican ...

  7. QTcpSocket And TCP Sticking analysis

    ---- My life , My little bit !! For two days Qt Simply implement a tcp Multithreading client, Record the knowledge here . One . Long connection and short connection 1. A long connection Client Fang and Server Fang first establishes a communication connection , After the connection is established, it keeps opening ...

  8. Regular expressions cheat sheet

  9. 【java】 And java Execution mechanism of code

    To be in JVM In the implementation of java The code has to be compiled as class file ,JDK How will Java Code compiled as class file , This mechanism is often called Java Source compilation mechanism . 1.JVM Defined class File format , But it's not defined as ...

  10. Go Revel - main Function analysis

    function revel On command , First, the entire project will be compiled , At compile time , Will be based on `app.conf` The configuration file generates two source files `tmp/main.go`.`routes/routes.go`, among `main.go` It's the whole project ...