iOS学习——第二天

第一部分

+方法[类名 函数名]

-方法[实例 函数名]

//Test.h

#import <Foundation/Foundation.h>


@interface Test : NSObject

-(void)test:(int)a;//“-”代表实例方法(instance)

+(void)test2:(int)b;//"+"代表静态方法

@end


//Test.m

#import "Test.h"


@implementation Test

-(void)test:(int)a 

{

    NSLog(@"-");

}

+(void)test2:(int)b

{

    NSLog(@"+");

}

@end


//AppDelegate.h

#import "AppDelegate.h"

#import "Test.h"

@implementation AppDelegate


- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions

{


    [Test test2:2];//静态方法可直接调用

    Test *t=[[Test alloc]init];//实例方法需要先实例化

    [t test:2];

     return YES;

}


Output:




第二部分  方法重载


//Parent.h

#import<Foundation/Foundation.h>


@ineterface Parent :NSObject

-(void)fun:(int)num;

@property (retain,nonatomic) NSMutableString *a;//retain相当于人工retain1

@end


//Parent.m

#import"Parent.h"


@implementation Parent

-(void)fun:(int)num

{

   NSLog(@"I'm parent");

}

@end


//Child.h

#import"Parent.h"

@interface Child :Parent

-(void)fun:(int)num;

@end


//Child.m

#import"Child.h"


@implementation Child

-(void)fun:(int)num

{

   NSLog(@"I'm child");

}

@end


//AppDelegate.m

#import"AppDelegate.h"

#import"Parent.h"

#import"Child.h"

@implementation AppDelegate


- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions

{

   // Override point for customization after application launch.

    Parent *p1=[[Child alloc]init];

    [p1 fun:3];

@end

//这个.m并不完整,只纪录了改动的部分。.h没有改动


output:



第三部分 引用计数(non-ARC手工释放)


方法:点工程名-PROJECT/TARGETS-搜“automatic”-Object-c Automatic Reference Co…./Objective-C Automatic Reference Co….的选项选为“NO”


- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions

{

   // Override point for customization after application launch.

    Parent *p1=[[Child alloc]init];

    [p1 fun:3];

    NSString *tests=@"tests";

    p1.a=[NSMutableStringstringWithFormat:@"%@",tests];

   int count=[p1.aretainCount];//获得引用计数的值,当retainCount==0时,释放内存

    NSLog(@"%d",count);

    [p1.aretain];//调用retain后,引用计数加1

    count=[p1.aretainCount];

    NSLog(@"%d",count);

    [p1.arelease];//调用release后,引用计数减1

    count=[p1.aretainCount];

    NSLog(@"%d",count);

@end

output:

有“retain”时@property (retain,nonatomic) NSMutableString *a;//retain相当于人工retain1



无“retain”时@property (nonatomic) NSMutableString *a;


//如果把NSMutableString改为NSString,或者赋一个常量,则引用计数(retainCount)始终为-1或很大的数(与机器有关),这是因为程序运行时分为代码区和数据区等,在数据区里有常量区,只有当应用程序退出时才释放


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值