SlideShare a Scribd company logo
1 of 20
MEMORY MANAGEMENT
CÁCH QUẢN LÝ BỘ NHỚ TRONG IOS
Presenter: Huong Nguyen
Skype: lan_huong_a3
NỘI DUNG
10/30/2013

Kháiniệm
 Cáccáchquảnlý
 Chuyển đổi giữa ARC và Non-ARC
 Nêndùngthếnào? Kết luận
 Bonus: Những điều cần biết


1
KHÁI NIỆM
10/30/2013



Quản lý bộ nhớ là quá trình cấp phát, sử dụng và giải
phóng bộ nhớ của ứng dụng.

Giải phóng bộ nhớ bằng tay:
 Không giải phóng bộ nhớ -> Gây ra rò rỉ -> Làm chậm
chương trình hoặc crash.
 Giải phóng bộ nhớ quá tay -> memory corruption ->
Crash.


2
CÁCCÁCHQUẢNLÝ
10/30/2013

Khi tạo 1 project, Cách quản lý bộ nhớ của 1 project sẽ
được thiết lập ở 1 trong 2 loại cơ bản:
 Non-ARC
 ARC
 Ngoài ra, có thể sử dụng kết hợp ARC và Non-ARC
trong 1 project

3
NON-ARC-QUY TẮC CƠ BẢN
10/30/2013

Chúngtasởhữuđối tượng (owned)
khisửdụnglệnhallochoặc copy đối tượngalloc,
allocWithZone:, copy, copyWithZone:, mutableCopy
mutableCopyWithZone: (1)
 Nếukhôngsởhữuđốitượng, nhưngvẫnmuốn lưu đối
tượng vào bộ nhớ để sử dụng lại (ownership
interest) retain (2)
 (1), (2) Khi không cần dùng đối tượng nữa phải
dùng release, autorelease để giải phóng đối tượng.
 Không phải (1), (2) thì không được phép release
đối tượng


4
NON-ARC: VÍ DỤ (1)
10/30/2013

UIButton *button = [UIButton alloc] init];
//do something with button
//…
[button release];

5
NON-ARC: VÍ DỤ (2)
10/30/2013

UIButton *button = [UIButton alloc] init];
UIButton *button2 = [button retain];
//do sth with button 2
[button release];
[button2 release];

6
NON ARC-CHIA SẺ
10/30/2013

UIButton *button = [[UIButton alloc] init];
button.titleLabel.text = @"click me";
[button release];

NSLog(@"Button title %@",button.titleLabel.text);

LEAK >< Crash
7
ARC
10/30/2013

Khi làm việc với Non-ARCmất nhiều thời gian
phải quản lý bộ nhớ, viết lệnh retain, release,
autorelease ARC: Tính năng quản lý bộ nhớ tự
động, trong quá trình project được compile, trình
biên dịch tự động chèn release, dealloc function
vào thay vì suy nghĩ xem nên đặt release, retain thế
nào.
  Code ngắn gọn hơn, ít stress hơn, hiệu quả hơn.
 Chỉ chạy được trên IOS 4.3 trở lên.


8
ARC VS NON ARC
10/30/2013

9
ARC-QUY TẮC CƠ BẢN
10/30/2013

Không dùng hàm dealloc, retain, release,
retainCount, autorelease nữa.
 Có thể implement hàm dealloc để quản lý tài
nguyên chứ không giải phóng bộ nhớ (VD: Set lại
delegate [systemClassInstance setDelegate:nil])
 không gọi hàm [super dealloc].
 Không được sử dụng object NSAutoreleasepool


10
ARC-QUY TẮC CƠ BẢN (2)
Tránh đặt tên varible bắt đầu bằng new, nếu lỡ rồi
thì phải sửa

10/30/2013



@property NSString *newTitle; Lỗi
@property (getter=theNewTitle) NSString *newTitle;



Tham khảo thêm:Transaction To Arc Release Notedeveloper.apple.com
11
ARC-LIFE TIME-PROPERTY ATTRIBUTES
10/30/2013

Non-ARC:
@property (retain) MyClass *myObject
 ARC: @property (strong) MyClass *myObject;


Non-ARC
@property (assign) MyClass *myObject
 ARC: @property (weak) MyClass *myObject;
 Nếu mặc định không khai báo strong hay weak 
Hiểu là strong.


12
ARC-LIFE TIME-VARIBLE QUALIFIER


__strong (default) sở hữu đối tượng
__weak có thể trỏ tới đối tượng, nhưng không thể sở
hữu đối tượng.

10/30/2013



__weak NSString *weakName = self.textField.text;



__unsafe_unretained: Được dùng cho những TH đặc
biệt như kiểu struct

struct MyStruct {

NSString __unsafe_unretained *text;
};



__autoreleasing: Được tự động giải phóng khi kết thúc
hàm

- (BOOL) doSomething:(NSError * __autoreleasing *)myError {
*myError = [[NSError alloc] init];
// ...
return NO;
}

13
KẾTHỢP ARC &NON ARC
-fno-obj-arc &-fobjc-arc

10/30/2013



14
CHUYỂN PROJECT NON-ARC SANG ARC
10/30/2013

15
NÊN DÙNG THẾ NÀO? KẾT
Nếu không vì lý do đặc biệt nào (đòi hỏi chạy trên
IOS version thấp hơn) nên dùng ARC.

10/30/2013



16
BONUS: NHỮNG ĐIỀU CẦN BIẾT
Iphone 3G có dung lượng Ram 128Mb, nhưng
phần lớn bộ nhớ được sử dụng cho HĐH, dung
lượng phục vụ cho app vào khoảng <40MB. Chúng
ta có thể gặp memory warning ngay cả khi sử dụng
3MB???

10/30/2013



17
THAM KHẢO
10/30/2013

Căn bản về quản lý bộ nhớ-Apple
 Transition To ARC Release Note-Apple
 Nên dùng ARC hay không?-Stackoverflow
 Một số lưu ý về quản lý bộ nhớ-akosma.com
 Tutorial về quản lý bộ nhớ


18
10/30/2013

Thank you

19

More Related Content

Featured

How Race, Age and Gender Shape Attitudes Towards Mental Health
How Race, Age and Gender Shape Attitudes Towards Mental HealthHow Race, Age and Gender Shape Attitudes Towards Mental Health
How Race, Age and Gender Shape Attitudes Towards Mental Health
ThinkNow
 
Social Media Marketing Trends 2024 // The Global Indie Insights
Social Media Marketing Trends 2024 // The Global Indie InsightsSocial Media Marketing Trends 2024 // The Global Indie Insights
Social Media Marketing Trends 2024 // The Global Indie Insights
Kurio // The Social Media Age(ncy)
 

Featured (20)

2024 State of Marketing Report – by Hubspot
2024 State of Marketing Report – by Hubspot2024 State of Marketing Report – by Hubspot
2024 State of Marketing Report – by Hubspot
 
Everything You Need To Know About ChatGPT
Everything You Need To Know About ChatGPTEverything You Need To Know About ChatGPT
Everything You Need To Know About ChatGPT
 
Product Design Trends in 2024 | Teenage Engineerings
Product Design Trends in 2024 | Teenage EngineeringsProduct Design Trends in 2024 | Teenage Engineerings
Product Design Trends in 2024 | Teenage Engineerings
 
How Race, Age and Gender Shape Attitudes Towards Mental Health
How Race, Age and Gender Shape Attitudes Towards Mental HealthHow Race, Age and Gender Shape Attitudes Towards Mental Health
How Race, Age and Gender Shape Attitudes Towards Mental Health
 
AI Trends in Creative Operations 2024 by Artwork Flow.pdf
AI Trends in Creative Operations 2024 by Artwork Flow.pdfAI Trends in Creative Operations 2024 by Artwork Flow.pdf
AI Trends in Creative Operations 2024 by Artwork Flow.pdf
 
Skeleton Culture Code
Skeleton Culture CodeSkeleton Culture Code
Skeleton Culture Code
 
PEPSICO Presentation to CAGNY Conference Feb 2024
PEPSICO Presentation to CAGNY Conference Feb 2024PEPSICO Presentation to CAGNY Conference Feb 2024
PEPSICO Presentation to CAGNY Conference Feb 2024
 
Content Methodology: A Best Practices Report (Webinar)
Content Methodology: A Best Practices Report (Webinar)Content Methodology: A Best Practices Report (Webinar)
Content Methodology: A Best Practices Report (Webinar)
 
How to Prepare For a Successful Job Search for 2024
How to Prepare For a Successful Job Search for 2024How to Prepare For a Successful Job Search for 2024
How to Prepare For a Successful Job Search for 2024
 
Social Media Marketing Trends 2024 // The Global Indie Insights
Social Media Marketing Trends 2024 // The Global Indie InsightsSocial Media Marketing Trends 2024 // The Global Indie Insights
Social Media Marketing Trends 2024 // The Global Indie Insights
 
Trends In Paid Search: Navigating The Digital Landscape In 2024
Trends In Paid Search: Navigating The Digital Landscape In 2024Trends In Paid Search: Navigating The Digital Landscape In 2024
Trends In Paid Search: Navigating The Digital Landscape In 2024
 
5 Public speaking tips from TED - Visualized summary
5 Public speaking tips from TED - Visualized summary5 Public speaking tips from TED - Visualized summary
5 Public speaking tips from TED - Visualized summary
 
ChatGPT and the Future of Work - Clark Boyd
ChatGPT and the Future of Work - Clark Boyd ChatGPT and the Future of Work - Clark Boyd
ChatGPT and the Future of Work - Clark Boyd
 
Getting into the tech field. what next
Getting into the tech field. what next Getting into the tech field. what next
Getting into the tech field. what next
 
Google's Just Not That Into You: Understanding Core Updates & Search Intent
Google's Just Not That Into You: Understanding Core Updates & Search IntentGoogle's Just Not That Into You: Understanding Core Updates & Search Intent
Google's Just Not That Into You: Understanding Core Updates & Search Intent
 
How to have difficult conversations
How to have difficult conversations How to have difficult conversations
How to have difficult conversations
 
Introduction to Data Science
Introduction to Data ScienceIntroduction to Data Science
Introduction to Data Science
 
Time Management & Productivity - Best Practices
Time Management & Productivity -  Best PracticesTime Management & Productivity -  Best Practices
Time Management & Productivity - Best Practices
 
The six step guide to practical project management
The six step guide to practical project managementThe six step guide to practical project management
The six step guide to practical project management
 
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...
 

Memory Management Object C - Quản lý bộ nhớ trong Object C

  • 1. MEMORY MANAGEMENT CÁCH QUẢN LÝ BỘ NHỚ TRONG IOS Presenter: Huong Nguyen Skype: lan_huong_a3
  • 2. NỘI DUNG 10/30/2013 Kháiniệm  Cáccáchquảnlý  Chuyển đổi giữa ARC và Non-ARC  Nêndùngthếnào? Kết luận  Bonus: Những điều cần biết  1
  • 3. KHÁI NIỆM 10/30/2013  Quản lý bộ nhớ là quá trình cấp phát, sử dụng và giải phóng bộ nhớ của ứng dụng. Giải phóng bộ nhớ bằng tay:  Không giải phóng bộ nhớ -> Gây ra rò rỉ -> Làm chậm chương trình hoặc crash.  Giải phóng bộ nhớ quá tay -> memory corruption -> Crash.  2
  • 4. CÁCCÁCHQUẢNLÝ 10/30/2013 Khi tạo 1 project, Cách quản lý bộ nhớ của 1 project sẽ được thiết lập ở 1 trong 2 loại cơ bản:  Non-ARC  ARC  Ngoài ra, có thể sử dụng kết hợp ARC và Non-ARC trong 1 project 3
  • 5. NON-ARC-QUY TẮC CƠ BẢN 10/30/2013 Chúngtasởhữuđối tượng (owned) khisửdụnglệnhallochoặc copy đối tượngalloc, allocWithZone:, copy, copyWithZone:, mutableCopy mutableCopyWithZone: (1)  Nếukhôngsởhữuđốitượng, nhưngvẫnmuốn lưu đối tượng vào bộ nhớ để sử dụng lại (ownership interest) retain (2)  (1), (2) Khi không cần dùng đối tượng nữa phải dùng release, autorelease để giải phóng đối tượng.  Không phải (1), (2) thì không được phép release đối tượng  4
  • 6. NON-ARC: VÍ DỤ (1) 10/30/2013 UIButton *button = [UIButton alloc] init]; //do something with button //… [button release]; 5
  • 7. NON-ARC: VÍ DỤ (2) 10/30/2013 UIButton *button = [UIButton alloc] init]; UIButton *button2 = [button retain]; //do sth with button 2 [button release]; [button2 release]; 6
  • 8. NON ARC-CHIA SẺ 10/30/2013 UIButton *button = [[UIButton alloc] init]; button.titleLabel.text = @"click me"; [button release]; NSLog(@"Button title %@",button.titleLabel.text); LEAK >< Crash 7
  • 9. ARC 10/30/2013 Khi làm việc với Non-ARCmất nhiều thời gian phải quản lý bộ nhớ, viết lệnh retain, release, autorelease ARC: Tính năng quản lý bộ nhớ tự động, trong quá trình project được compile, trình biên dịch tự động chèn release, dealloc function vào thay vì suy nghĩ xem nên đặt release, retain thế nào.   Code ngắn gọn hơn, ít stress hơn, hiệu quả hơn.  Chỉ chạy được trên IOS 4.3 trở lên.  8
  • 10. ARC VS NON ARC 10/30/2013 9
  • 11. ARC-QUY TẮC CƠ BẢN 10/30/2013 Không dùng hàm dealloc, retain, release, retainCount, autorelease nữa.  Có thể implement hàm dealloc để quản lý tài nguyên chứ không giải phóng bộ nhớ (VD: Set lại delegate [systemClassInstance setDelegate:nil])  không gọi hàm [super dealloc].  Không được sử dụng object NSAutoreleasepool  10
  • 12. ARC-QUY TẮC CƠ BẢN (2) Tránh đặt tên varible bắt đầu bằng new, nếu lỡ rồi thì phải sửa 10/30/2013  @property NSString *newTitle; Lỗi @property (getter=theNewTitle) NSString *newTitle;  Tham khảo thêm:Transaction To Arc Release Notedeveloper.apple.com 11
  • 13. ARC-LIFE TIME-PROPERTY ATTRIBUTES 10/30/2013 Non-ARC: @property (retain) MyClass *myObject  ARC: @property (strong) MyClass *myObject;  Non-ARC @property (assign) MyClass *myObject  ARC: @property (weak) MyClass *myObject;  Nếu mặc định không khai báo strong hay weak  Hiểu là strong.  12
  • 14. ARC-LIFE TIME-VARIBLE QUALIFIER  __strong (default) sở hữu đối tượng __weak có thể trỏ tới đối tượng, nhưng không thể sở hữu đối tượng. 10/30/2013  __weak NSString *weakName = self.textField.text;  __unsafe_unretained: Được dùng cho những TH đặc biệt như kiểu struct struct MyStruct { NSString __unsafe_unretained *text; };  __autoreleasing: Được tự động giải phóng khi kết thúc hàm - (BOOL) doSomething:(NSError * __autoreleasing *)myError { *myError = [[NSError alloc] init]; // ... return NO; } 13
  • 15. KẾTHỢP ARC &NON ARC -fno-obj-arc &-fobjc-arc 10/30/2013  14
  • 16. CHUYỂN PROJECT NON-ARC SANG ARC 10/30/2013 15
  • 17. NÊN DÙNG THẾ NÀO? KẾT Nếu không vì lý do đặc biệt nào (đòi hỏi chạy trên IOS version thấp hơn) nên dùng ARC. 10/30/2013  16
  • 18. BONUS: NHỮNG ĐIỀU CẦN BIẾT Iphone 3G có dung lượng Ram 128Mb, nhưng phần lớn bộ nhớ được sử dụng cho HĐH, dung lượng phục vụ cho app vào khoảng <40MB. Chúng ta có thể gặp memory warning ngay cả khi sử dụng 3MB??? 10/30/2013  17
  • 19. THAM KHẢO 10/30/2013 Căn bản về quản lý bộ nhớ-Apple  Transition To ARC Release Note-Apple  Nên dùng ARC hay không?-Stackoverflow  Một số lưu ý về quản lý bộ nhớ-akosma.com  Tutorial về quản lý bộ nhớ  18