• OC对象的动态和静态构造区别


    Student.h:

    #import <Foundation/Foundation.h>
    
    @interface Student : NSObject
    
    @property(nonatomic,retain) NSString * name;
    
    @property(nonatomic,assign) int age;
    
    @end

    Student.m:

    #import "Student.h"
    
    @implementation Student
    
    //动态方法,在main函数中类alloc了之后调用,但是要手动管理内存,要手动释放
    
    -(id) initWithAge:(int)age{
    
        if (self == [super init]) {
    
            _age = age;
    
        }
    
        return self;
    
    }
    
     
    
    //静态构造方法,在main函数中不需要你手动管理内存释放
    
    +(id)studentWithAge:(int)age{
    
        Student *stu = [[[Student alloc] init] autorelease];
    
        stu.age = age;
    
        return stu;
    
    }
    
     
    
    -(NSString *)description{
    
        return [NSString stringWithFormat:@"name:%@ age:%i创建了",_name,_age];
    
    }
    
     
    
    -(void)dealloc{
    
        NSLog(@"name:%@ age:%i被释放了",_name,_age);
    
        [_name release];
    
        [super dealloc];
    
    }
    
    @end
    

      

    main

     1 #import <Foundation/Foundation.h>
     2 
     3 #import "Student.h"
     4 
     5 int main(int argc, const char * argv[])
     6 
     7 {
     8 
     9     @autoreleasepool {
    10 
    11         //动态方法需要手动释放内存
    12 
    13         Student *stu1= [[Student alloc] initWithAge:10];
    14 
    15         stu1.name = @"dingxiaowei";
    16 
    17         NSLog(@"%@",stu1);
    18 
    19         [stu1 release];
    20 
    21         //静态构造方法不需要你管理内存
    22 
    23         Student *stu2 =[Student studentWithAge:20];
    24 
    25         stu2.name = @"wangning";
    26 
    27         NSLog(@"%@",stu2);
    28 
    29     }
    30 
    31     return 0;
    32 
    33 }
    

      

    结果:

    OC对象的动态和静态构造区别 - 蓬莱仙羽 - 蓬莱仙羽
    感谢来访,共同学习!
  • 相关阅读:
    JQuery hover鼠标变换
    装饰者模式
    principle04
    Method Injection
    观察者模式
    Java SPI
    Redis--学习01
    OO设计中5大原则
    knowledge
    策略模式
  • 原文地址:https://www.cnblogs.com/dingxiaowei/p/3222689.html
Copyright © 2020-2023  润新知