完美釋放執行個體變數的記憶體,定義成宏的形式,執行個體成宏

來源:互聯網
上載者:User

完美釋放執行個體變數的記憶體,定義成宏的形式,執行個體成宏


完美釋放記憶體,麻煩自己方便他人...

定義成宏的形式:

#define RELEASE_SAFE(_Pointer) do{[_Pointer release],_Pointer = nil;}while(0) 

例:

//姓名

@property (nonatomic,copy)NSString *name;

//性別

@property (nonatomic,copy)NSString *gender;

//年齡

@property (nonatomic,copy)NSString *age;

//連絡方式

@property (nonatomic,copy)NSString *phoneNumber;

//圖片名

@property (nonatomic,copy)NSString *imageName;

- (void)dealloc

{

   RELEASE_SAFE(_name);

   RELEASE_SAFE(_gender);

   RELEASE_SAFE(_age);

   RELEASE_SAFE(_phoneNumber);

   RELEASE_SAFE(_imageName);

    [super  dealloc];

}



define怎定義帶參數的宏

define如何對帶參數宏定義
解釋一下如下代碼
#define __TEXT(quote) quote

回答如下:
#define __TEXT(quote) quote : 定義帶參數宏__TEXT 為他的參數
程式中遇到__TEXT(參數) 用他的 參數 直接代替 。
例如:
printf(__TEXT("this is test!"));
結果和 printf("this is test!"); 是一樣的
在VC++6.0中 定義了 __T(x) 和 _T(x) 與 __TEXT(quote) quote 是一樣的
例如:CFileDialog OpenDlg(TRUE,_T("All File"),
_T("*.*"),OFN_HIDEREADONLY|OFN_OVERWRITEPROMPT,
(_T("All File(*.*)|*.*")));

對於帶參宏定義:形式上類似函數,編譯時間直接鑲嵌到調用該代碼的地方
例如我要檢測變數的某一位可以定義成宏定義函數形式
#define BITN(var,n) (var&(1<<n))

當我使用時可以直接調用:
int var=0x45;
if(BITN(var,2)) printf(__TEXT("bit3=1"));
等於if((var&(1<<2)))printf("bit3=1");

又如:當條件滿足時輸出本檔案名稱和該函數的調用行號
#define AssertFileLineE(expression) {\
if(!(expression)) \
printf("filename:%s,line number:%d",__FILE__,__LINE__);\
}

調用形式:

假設檔案為:test.c
行號為後面的注釋所示
#include“stdio.h” //0行
#include“stdlib.h” //1行
main() //2行
{ //3行
//4行
AssertFileLineE(rand(100%2)==0);//5行,當隨機數為偶數時輸出main函數所在的檔案名稱和該行的行號,輸出結果為:filename:test.c
,line number:5
}
 
c++,函數

3樓的答案基本是對的,但是(1)從效率而言pi最好不要定義成變數,定義成宏常量要好得多;(2)double area...後面加的分號使函數徹底錯了,所以3樓的程式也不能運行;(3)從提問者寫的程式來看,可能函數的結構和形參定義還沒有搞清楚,建議照書寫幾個程式訓練訓練。

#include "iostream.h"
#include "math.h"
#define PI 3.14159

double area(double r)
{ double area;
area=r*r*PI;
return area;
}
void main()
{
double r;
cout<<"輸入半徑r"<<endl;
cin>>r;
cout<<"面積是"<<area(r)<<endl;
}
 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

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.