Showing posts with label memory-leaks. Show all posts
Showing posts with label memory-leaks. Show all posts

Wednesday, May 23, 2018

Keyboard Extension Memory Leak?

Leave a Comment

I am building a custom keyboard extension (iOS 9+) and have found a more than annoying memory leak.

Just from using the template provided by Apple, there appears to be a nasty memory leak derived from an NSMutableDictionary cycle.

When leaving an application (in this test case the Messages app) then returning, this leak occurs. Typically 25 leaked items (seen in the photos of Xcode's Instruments7 below)

enter image description here

enter image description here

I have literally done nothing to the template but receive this leak. Does anyone have any suggestions on how to fix this?...

EDIT: Because Xcode tends to exaggerate (handle) memory usages differently than any physical device (my case iPhone 6s iOS 11.2), I'm not entirely sure this will even have any impact to the performance / run-life of my keyboard. From testing I did not find any issues. Going back and forth to and from Safari or Messages did not crash or switch back to the default keyboard. Nevertheless... memory leak... not good.

1 Answers

Answers 1

I sometimes find sporadic leaks that Xcode Instruments flags as such, but I cannot do anything about it, because the problem is in Apple's code, which is apparently your case. The only thing you can do is to file a bug report and go on with your project, in particular if the leak is sporadic, and is only a question of a few bytes, and does not build up in time. In summary, if these conditions apply, I wouldn't worry too much about it.

Read More

Friday, April 27, 2018

Instruments show “_NSContiguousstring” memory leak when scrolling UITableView

Leave a Comment

I have a UItableView which consist of 10 element. I opened Instruments to catch the memory leaks and when I scroll tableView, It started to give memory leaks. In Instruments I tried to find which causes the leaks but can't figure out, It says "_NScontiguousstring" for whole leaks.

I found some solutions for Objective-C which they check If cell is nil in "CellForRowAt" function. I don't think it is useful for Swift but I tried and as expected It doesn't work.

Memory Leak UITableView

My question is what can cause this kind of memory leak?

Controller Class;

class TableViewController: UITableViewController { let teamModel = TeamModel(uid: "adsada", name: "First Team ", idea: "idea 1", slogan: "Slogan 1", university: "dasda", image: "info", isActive: true) let teamModel2 = TeamModel(uid: "adsada", name: "Team 2", idea: "idea 2", slogan: "adasd", university: "dasda", image: "info", isActive: true) let teamModel3 = TeamModel(uid: "adsada", name: "Team 3", idea: "idea 3", slogan: "adasd", university: "dasda", image: "info", isActive: true) let teamModel4 = TeamModel(uid: "adsada", name: "Team 4", idea: "idea 4", slogan: "adasd", university: "dasda", image: "info", isActive: true) let teamModel5 = TeamModel(uid: "adsada", name: "Team 5", idea: "idea 5", slogan: "adasd", university: "dasda", image: "info", isActive: true) let teamModel6 = TeamModel(uid: "adsada", name: "Team 6", idea: "idea 6", slogan: "adasd", university: "dasda", image: "info", isActive: true) let teamModel7 = TeamModel(uid: "adsada", name: "Team 7", idea: "idea 7", slogan: "adasd", university: "dasda", image: "info", isActive: true)  var data: [TeamModel] = [] override func viewDidLoad() {     super.viewDidLoad()     tableView.register(mainTableCell.self, forCellReuseIdentifier: "mainTableCell")     data = [teamModel,teamModel2,teamModel3,teamModel4,teamModel5,teamModel6,teamModel7] } // MARK: - Table view data source override func numberOfSections(in tableView: UITableView) -> Int {     // #warning Incomplete implementation, return the number of sections     return 1 } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {     // #warning Incomplete implementation, return the number of rows     return data.count } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {     let cell = tableView.dequeueReusableCell(withIdentifier: "mainTableCell", for: indexPath) as! mainTableCell     let cell_data = data[indexPath.row]      cell.cell_data = cell_data      return cell } override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {     return 120 } } 

Cell Class;

class mainTableCell: UITableViewCell{ var cell_data: TeamModel?{     didSet{         guard let unwrappedCell = cell_data else { return }         if let url = unwrappedCell.imageURL{             profileImage.image = UIImage(named: "info")         } else{             self.profileImage.image = UIImage(named: "info")         }         self.teamLbl.text = unwrappedCell.name        mainBackground.backgroundColor = UIColor.gray     } }  let mainBackground: UIView = {     let v = UIView()     v.layer.cornerRadius = 8     v.layer.masksToBounds = true     return v }()  var isVoteable: Bool = false  //let shadowView = ShadowView()  let profileImage: UIImageView = {     let imageView = UIImageView()     imageView.contentMode = .scaleAspectFill     imageView.clipsToBounds = true     imageView.layer.masksToBounds = true     return imageView }()  let teamLbl: UILabel = {     let label = UILabel()     label.textColor = UIColor.black     label.numberOfLines = 1     label.adjustsFontSizeToFitWidth = true     return label }()  let myVoteLbl: UILabel = {     let l = UILabel()     l.text = "Oyum: --"     return l }() let voteBtn: UIButton = {    let b = UIButton(type: .custom)     b.setImage(UIImage(named: "info"), for: .normal)      return b }() override init(style: UITableViewCellStyle, reuseIdentifier: String?){     super.init(style: style, reuseIdentifier: reuseIdentifier)      setupViews() } func setupViews() {      self.backgroundColor = UIColor.white       self.mainBackground.addSubview(profileImage)     self.mainBackground.addSubview(teamLbl)     self.mainBackground.addSubview(voteBtn)     self.mainBackground.addSubview(myVoteLbl)      //self.addSubview(shadowView)     self.addSubview(mainBackground)     self.backgroundColor = UIColor.clear      profileImage.translatesAutoresizingMaskIntoConstraints = false     teamLbl.translatesAutoresizingMaskIntoConstraints = false     voteBtn.translatesAutoresizingMaskIntoConstraints = false     myVoteLbl.translatesAutoresizingMaskIntoConstraints = false     mainBackground.translatesAutoresizingMaskIntoConstraints = false     //shadowView.translatesAutoresizingMaskIntoConstraints = false  } override func layoutSubviews() {     super.layoutSubviews()     // self.setCircularImageView()     mainBackground.anchor(self.topAnchor, left: self.leftAnchor, bottom: self.bottomAnchor, right: self.rightAnchor, topConstant: 10, leftConstant: 10, bottomConstant: 10, rightConstant: 10, widthConstant: 0, heightConstant: 0)     // shadowView.anchor(self.topAnchor, left: self.leftAnchor, bottom: self.bottomAnchor, right: self.rightAnchor, topConstant: 5, leftConstant: 5, bottomConstant: 5, rightConstant: 5, widthConstant: 0, heightConstant: 0)      profileImage.anchor(nil, left: self.mainBackground.leftAnchor, bottom: nil, right: nil, topConstant: 0, leftConstant: 10, bottomConstant: 0, rightConstant: 0, widthConstant: 60, heightConstant: 60)     profileImage.anchorCenterYToSuperview()       teamLbl.anchor(self.mainBackground.topAnchor, left: profileImage.rightAnchor, bottom: nil, right: self.voteBtn.leftAnchor, topConstant: 20, leftConstant: 20, bottomConstant: 0, rightConstant: 0, widthConstant: 0, heightConstant: 40)     myVoteLbl.anchor(nil, left: profileImage.rightAnchor, bottom: self.mainBackground.bottomAnchor, right: nil, topConstant: 0, leftConstant: 20, bottomConstant: 20, rightConstant: 0, widthConstant: 0, heightConstant: 0)      voteBtn.anchor(nil, left: nil, bottom: nil, right: self.mainBackground.rightAnchor, topConstant: 0, leftConstant: 0, bottomConstant: 0, rightConstant: 0, widthConstant: 80, heightConstant: 80)     voteBtn.anchorCenterYToSuperview() }  func setCircularImageView() {     self.profileImage.layer.cornerRadius = CGFloat(roundf(Float(self.profileImage.frame.size.width / 2.0))) } required init?(coder aDecoder: NSCoder) {     fatalError("init(coder:) has not been implemented") } } 

First SS

Second SS

EDIT: I add prepareForReuse method regarding to below answer but now cells show just white. Am I doing something wrong?

    override func prepareForReuse() {     super.prepareForReuse()      teamLbl.text = ""     myVoteLbl.text = ""     profileImage.image = nil } 

I also make cell_data variable "weak var cell_data: TeamModel? and nil it in prepareForReuse() method but still same leaks are coming.

EDIT 2: Full project;

https://github.com/emreond/TableView-Memory-Leak-Project

EDIT 3: I found that when I add If check and change attributes inside didst of cell_data, some cells views look ruined. For example when I change teamLbl text color inside cell_data. In some cells, It looks ruined.

1 Answers

Answers 1

First things first.

Inside layoutSubviews you are setting anchores. Why ? It's going to be called each time your cells will be called.

Instead of this, move

// self.setCircularImageView()     mainBackground.anchor(self.topAnchor, left: self.leftAnchor, bottom: self.bottomAnchor, right: self.rightAnchor, topConstant: 10, leftConstant: 10, bottomConstant: 10, rightConstant: 10, widthConstant: 0, heightConstant: 0)     // shadowView.anchor(self.topAnchor, left: self.leftAnchor, bottom: self.bottomAnchor, right: self.rightAnchor, topConstant: 5, leftConstant: 5, bottomConstant: 5, rightConstant: 5, widthConstant: 0, heightConstant: 0)      profileImage.anchor(nil, left: self.mainBackground.leftAnchor, bottom: nil, right: nil, topConstant: 0, leftConstant: 10, bottomConstant: 0, rightConstant: 0, widthConstant: 60, heightConstant: 60)     profileImage.anchorCenterYToSuperview()       teamLbl.anchor(self.mainBackground.topAnchor, left: profileImage.rightAnchor, bottom: nil, right: self.voteBtn.leftAnchor, topConstant: 20, leftConstant: 20, bottomConstant: 0, rightConstant: 0, widthConstant: 0, heightConstant: 40)     myVoteLbl.anchor(nil, left: profileImage.rightAnchor, bottom: self.mainBackground.bottomAnchor, right: nil, topConstant: 0, leftConstant: 20, bottomConstant: 20, rightConstant: 0, widthConstant: 0, heightConstant: 0)      voteBtn.anchor(nil, left: nil, bottom: nil, right: self.mainBackground.rightAnchor, topConstant: 0, leftConstant: 0, bottomConstant: 0, rightConstant: 0, widthConstant: 80, heightConstant: 80)     voteBtn.anchorCenterYToSuperview() 

Just bellow setupViews() call.

Next thing is that you didn't implement prepareForReuse(), you need to nil the values which u are setting in cellForRow, willDislayCell` etc.

EDIT

var cell_data: TeamModel? - Marking it as optional doesn't make it weak reference, mark it as weak var and nil it every time cell gets reused.

Read More

Thursday, February 8, 2018

UIImagePickerController leaking on iOS 11

Leave a Comment

I've configured my UIImagePickerController for taking an image and for recording a video both independently. The UIImagePickerController is directly called from an @IBAction (by a UIButton). I receive both UIImage and URL from the video in the imagePickerController delegate method and print them for testing purposes.

After waiting a little while (10 seconds) I select Xcode's "View Memory Graph History" in which I can see that in both testing cases I have memory leaks and also cyclic references. I can also see those memory leaks in Instruments if someone thinks it's an Xcode bug.

This happens when I record a video:

memory leaks video

And this happens when I take a picture:

memory leaks photo

You can reproduce this results with this code on a iOS 11.2 device (I don't think simulators would work):

import UIKit  class ViewController: UIViewController, UIImagePickerControllerDelegate, UINavigationControllerDelegate {      override func viewDidLoad() {         super.viewDidLoad()     }      override func didReceiveMemoryWarning() {         super.didReceiveMemoryWarning()     }      @IBAction func takePhoto(_ sender: Any) {          let picker = UIImagePickerController()         picker.delegate = self         picker.sourceType = .camera         picker.allowsEditing = false          self.present(picker, animated: true, completion: nil)     }      @IBAction func recordVideo(_ sender: Any) {          let picker = UIImagePickerController()         picker.delegate = self         picker.sourceType = .camera         picker.allowsEditing = false         picker.mediaTypes = ["public.movie"]         picker.videoQuality = .typeHigh          self.present(picker, animated: true, completion: nil)     }      func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String: Any]) {          picker.dismiss(animated: true, completion: nil)          if let image = info[UIImagePickerControllerOriginalImage] as? UIImage {             print(image.size)         }          if let video = info[UIImagePickerControllerMediaURL] as? URL {             print(video.path)         }     }      func imagePickerControllerDidCancel(_ picker: UIImagePickerController) {         picker.dismiss(animated: true, completion: nil)     }  } 

Now my question is: Can I fix those with some workaround or am I doing something wrong in my code, is this a bug by Apple, should I just ignore it?

Edit: If anyone wants to take a look at the whole project: https://github.com/ph1ps/UIImagePickerLeak

2 Answers

Answers 1

I would say just ignore the "leaks" you are seeing. While, I don't have any code to back this up, I do have some experience finding and fixing memory leaks on-the-job. In my experience, when you're finding leaks, you look for smoking guns. So for the memory graph history, I would suspect that there might be a memory leak if there were hundreds or thousands of instances of some type leaked. This goes for mobile apps as well. From what I can see from your screenshots, you're leaking at most 1k, which (assuming there even is a leak) is pretty trivial. As such, you really don't appear to have a leak.

Answers 2

I add some code to prove there is no memory leak. You can judge it either by my code or memory graph. I've already made a pull request.

https://github.com/Andy1984/UIImagePickerLeak

Read More

Friday, February 2, 2018

Activity taking 140mb memory

Leave a Comment

I'm trying to create a social media application. But it's taking about 300mb memory. So i had 5 fragments containing posts on my homepage. And overall the memory usage was 250-300mb

Then for testing, I disabled those fragments but still home activity is consuming 140mb without any big operations.

So,

here is my class

public class HomePage extends AppCompatActivity {     private Drawer result = null;     private Boolean isCoverEdit = false, isProfileEdit = false;     String username;     private RelativeLayout splash;     private Toolbar toolbar;     private StorageReference mStorage;     private ProgressDialog progressDialog;     private ImageView searchBtn;     private AHBottomNavigationViewPager fragContainer;     private AHBottomNavigation bottomNavigation;     private ImageView postBtn;     private View child;     private ImageView cover;     private CircleImageView profilePic;     private TextView star;     private TextView id;     private PopupMenu p;       @Override     protected void onCreate(Bundle savedInstanceState) {         super.onCreate(savedInstanceState);         setContentView(R.layout.activity_home_page);         if (FirebaseAuth.getInstance().getCurrentUser() == null) {             Intent i = new Intent(HomePage.this, Login.class);             startActivity(i);             finish();         } else {             getUsername();             initiateViews();             setupOnClickListeners();             setupBottomNavigation();              mStorage = FirebaseStorage.getInstance().getReference();             progressDialog = new ProgressDialog(this);          }       } 

Functions

    private void initiateViews() {         splash = findViewById(R.id.splash);         searchBtn = findViewById(R.id.search);         fragContainer = findViewById(R.id.frame);         toolbar = findViewById(R.id.toolbar);         bottomNavigation = findViewById(R.id.bottom_navigation);         postBtn = findViewById(R.id.post);         child = getLayoutInflater().inflate(R.layout.header, null);         profilePic = child.findViewById(R.id.pic);         id = child.findViewById(R.id.id);         cover = child.findViewById(R.id.cover);         star = child.findViewById(R.id.karma);     }   private void getUsername() {         username = new UserData(this).getUsername();          if (username==null){             FirebaseDatabase.getInstance().getReference().child("users").child(FirebaseAuth.getInstance().getCurrentUser().getUid()).child("username").addListenerForSingleValueEvent(new ValueEventListener() {                 @Override                 public void onDataChange(DataSnapshot dataSnapshot) {                     username = dataSnapshot.getValue(String.class);                     SharedPreferences settings = getSharedPreferences("AyePref", MODE_PRIVATE);                     SharedPreferences.Editor editor = settings.edit();                     editor.putString("username", username);                     editor.apply();                     setupNavigationDrawer();                     FirebaseDatabase.getInstance().getReference().child("userdata").child(username).child("token").setValue(FirebaseInstanceId.getInstance().getToken());                  }                  @Override                 public void onCancelled(DatabaseError databaseError) {                  }             });         }else {             setupNavigationDrawer();             FirebaseDatabase.getInstance().getReference().child("userdata").child(username).child("token").setValue(FirebaseInstanceId.getInstance().getToken());         }     }      private void setupNavigationDrawer() {         result = new DrawerBuilder()                 .withActivity(HomePage.this)                 .withHeader(child)                 .withDisplayBelowStatusBar(false)                 .withTranslucentStatusBar(false)                 .withDrawerLayout(R.layout.material_drawer_fits_not)                 .addDrawerItems(                         new PrimaryDrawerItem().withName("Favourites").withIcon(GoogleMaterial.Icon.gmd_forum),                         new PrimaryDrawerItem().withName("Settings").withIcon(GoogleMaterial.Icon.gmd_settings),                         new PrimaryDrawerItem().withName("Contact").withIcon(GoogleMaterial.Icon.gmd_contact_mail),                         new PrimaryDrawerItem().withName("Commands").withIcon(GoogleMaterial.Icon.gmd_help),                         new PrimaryDrawerItem().withName("Log Out").withIcon(GoogleMaterial.Icon.gmd_security)                 )                  .withOnDrawerItemClickListener(new Drawer.OnDrawerItemClickListener() {                     @Override                     public boolean onItemClick(View view, int position, IDrawerItem drawerItem) {                         if (drawerItem instanceof Nameable) {                             FragmentTransaction t = getSupportFragmentManager().beginTransaction();                             switch (position) {                                 case 3:                                     final Intent emailIntent = new Intent(android.content.Intent.ACTION_SEND);                                     emailIntent.setType("plain/text");                                     emailIntent.putExtra(android.content.Intent.EXTRA_EMAIL, new String[]{"ayesupport@yandex.com"});                                     startActivity(Intent.createChooser(emailIntent, "Send mail..."));                                     break;                                 case 5:                                      break;                                 case 2:                                     Intent i= new Intent(HomePage.this, SettingsActivity.class);                                     startActivity(i);                                     break;                                 case 4:                                     Intent i2 = new Intent(HomePage.this,CommandsPage.class);                                     startActivity(i2);                                     break;                              }                           }                          return false;                     }                 }).build();          FirebaseDatabase.getInstance().getReference().child("userdata").child(username).addListenerForSingleValueEvent(new ValueEventListener() {             @Override             public void onDataChange(DataSnapshot dataSnapshot) {                 try {                     Glide.with(HomePage.this).load(dataSnapshot.child("pic").getValue(String.class)).override(100,100).thumbnail(0.5f).into(profilePic);                     //Glide.with(HomePage.this).load(dataSnapshot.child("cover").getValue(String.class)).into(cover);                  } catch (Exception e) {                     e.printStackTrace();                 }                 id.setText(username);                 star.setText("4.7");              }              @Override             public void onCancelled(DatabaseError databaseError) {              }         });     }      private void setupBottomNavigation() {         AHBottomNavigationItem item1 = new AHBottomNavigationItem("Topics", new IconicsDrawable(this, GoogleMaterial.Icon.gmd_whatshot));         AHBottomNavigationItem item2 = new AHBottomNavigationItem("Rooms", new IconicsDrawable(this, GoogleMaterial.Icon.gmd_group_work));         AHBottomNavigationItem item3 = new AHBottomNavigationItem("Contacts", new IconicsDrawable(this, GoogleMaterial.Icon.gmd_people));         AHBottomNavigationItem item4 = new AHBottomNavigationItem("Leaderboard", new IconicsDrawable(this, GoogleMaterial.Icon.gmd_star));         AHBottomNavigationItem item5 = new AHBottomNavigationItem("Stats", new IconicsDrawable(this, GoogleMaterial.Icon.gmd_insert_chart));         bottomNavigation.addItem(item1);         bottomNavigation.addItem(item2);         bottomNavigation.addItem(item3);         bottomNavigation.addItem(item4);         bottomNavigation.addItem(item5);         bottomNavigation.setInactiveColor(R.color.md_grey_800);         bottomNavigation.setAccentColor(R.color.md_grey_600);         bottomNavigation.setTitleState(AHBottomNavigation.TitleState.ALWAYS_HIDE);         fragContainer.setOffscreenPageLimit(4);         HomePageAdapter adapter = new HomePageAdapter(getSupportFragmentManager());         setSupportActionBar(toolbar);         toolbar.setNavigationIcon(R.drawable.ic_menu_white_24dp);         //fragContainer.setAdapter(adapter);         bottomNavigation.setOnTabSelectedListener(new AHBottomNavigation.OnTabSelectedListener() {             @Override             public boolean onTabSelected(int position, boolean wasSelected) {                 //fragContainer.setCurrentItem(position);                 return wasSelected;              }         });     } 

Full Class : here In that class no fragments are added but the memory usage is 120-140

Memory Usage

I'm sure, I'm repeating the same mistakes in all other activities or fragments. Once I know the problem I can fix it for other parts. Heap Dump

Need Help :(

3 Answers

Answers 1

I think it is normal. It is not eating 140MB of RAM actually. On new Android Monitor of AS3 numbers are a bit different than previous AS2. In the user guide here, it is written:

When compared to memory counts from the previous Android Monitor tool, the new Memory Profiler records your memory differently, so it might seem like your memory use is now higher. The Memory Profiler monitors some extra categories that increase the total, but if you only care about the Java heap memory, then the "Java" number should be similar to the value from the previous tool.

And although the Java number probably doesn't exactly match what you saw in Android Monitor, the new number accounts for all physical memory pages that have been allocated to your app's Java heap since it was forked from Zygote. So this provides an accurate representation of how much physical memory your app is actually using.

Currently, the Memory Profiler also shows some false-positive native memory usage in your app that actually belongs to the profiling tools. Up to 10MB of memory is added for ~100k objects. In a future version of the tools, these numbers will be filtered out of your data.

I used to see 200MB+ on my previous app that has 4 fragments with bottom navigation (and found nothing on Leakcanary).

Answers 2

maybe this can help ..

check your

  • cover image
  • profile picture
  • splash screen image

check the size of the images they can effect the memory so bad !

in your code you used

UCrop.of(absolutePath, Uri.parse(imageURI))                         .withAspectRatio(16, 9)                         .withMaxResultSize(1280, 720)                         .start(HomePage.this); 

it’s not worth loading a 1024x768 pixel image into memory if it will eventually be displayed in a 128x96 pixel thumbnail in an ImageView.

thats mean you must be specific or if you need this quality use it but make sure this will cost a lot of memory.

take a look here

Load a Scaled Down Version into Memory

and there if the images that u use in the project as a splash screen you can use a tools Optimize your images with a perfect balance in quality and file size.

Tools - check this :

TinyPNG - Smart PNG and JPEG compression

Optimizilla

Answers 3

I would recommend you to check you resources. The drawable folder may contain pictures and also check for musics. Check the splash image size, if there are musics, check the size of it and also for videos.

Read More

Monday, December 25, 2017

`Unknown` (`Other`) memory leak in Android?

Leave a Comment

Android Studio Memory Profiler reports allocations in Others category.

enter image description here

According to https://developer.android.com/studio/profile/memory-profiler.html: Other: Memory used by your app that the system isn't sure how to categorize.

If we dig deeper, similar memory footprint information can be retrieved at runtime using https://developer.android.com/reference/android/os/Debug.MemoryInfo.html#getMemoryStat(java.lang.String)

It looks like Others in Android Studio Memory Profiler corresponds to summary.private-other in Debug.MemoryInfo class. That parameter is reported as:

public int getSummaryPrivateOther() {             return getTotalPrivateClean()               + getTotalPrivateDirty()               - getSummaryJavaHeap()               - getSummaryNativeHeap()               - getSummaryCode()               - getSummaryStack()               - getSummaryGraphics();         } 

Which kind of memory allocations end up in that category? It is obviously not Java, Native, Code, Stack and Graphics.

If my app (with enormously large codebase so I can't really pin point a certain code that causes it) consumes a lot of Other memory, is there a certain source/pattern that leads to such consumption?

Edit 1 I was able to partially answer the first part my own question:

Which kind of memory allocations end up in that category? It is obviously not Java, Native, Code, Stack and Graphics.

RAM info can also be retrieved using adb shell dumpsys meminfo <your proc name> and typically looks like:

enter image description here

Experimentally, I can see that Unknown is most likely included into Private Other. Which raises the next question: what is Unknown? According to https://developer.android.com/studio/command-line/dumpsys.html#meminfo:

Any RAM pages that the system could not classify into one of the other more specific items. Currently, this contains mostly native allocations, which cannot be identified by the tool when collecting this data due to Address Space Layout Randomization (ASLR). Like the Dalvik heap, the Pss Total for Unknown takes into account sharing with Zygote, and Private Dirty is unknown RAM dedicated to only your app.

It looks like it's still native allocations. Identifiable Native allocations end up in Native category, however, Native allocations whose data is no longer identifiable due to ASLR seem to end up in Unknown.

The main question however still holds:

If my app (with enormously large codebase so I can't really pin point a certain code that causes it) consumes a lot of Other memory, is there a certain source/pattern that leads to such consumption? I'm looking for answers such as hanging threads, open cursors, webviews and etc.

0 Answers

Read More

Sunday, November 12, 2017

Android Volley Memory Leaks

Leave a Comment

I use google's volley library and I have been battling memory leaks in my apps for weaks now. I have done soo much research and tried soo much already but now I just do not know what to do. This is a sample code:

SplashActivity.java

public class SplashActivity extends AppCompatActivity {      Context mContext;     AuthRequest mAuthRequest;     GetTokenOnSuccessListener mGetTokenOnSuccessListener;     GetTokenOnErrorListener mGetTokenOnErrorListener;     private ConfigTable mConfigTable;      @Override     protected void onCreate(Bundle savedInstanceState) {         super.onCreate(savedInstanceState);         initialiseViewsAndComponents();     }      @Override     protected void onStart() {         super.onStart();         getAuthToken();     }      private void initialiseViewsAndComponents() {         mContext = SplashActivity.this;         mAuthRequest = new AuthRequest(mContext);         mGetTokenOnSuccessListener = new GetTokenOnSuccessListener(mContext);         mGetTokenOnErrorListener = new GetTokenOnErrorListener(mContext);         mConfigTable = new ConfigTable(mContext);     }      private void getAuthToken() {         if (!mConfigTable.get("INITIALISED").equals("")) {             mAuthRequest.guest(mGetTokenOnSuccessListener, mGetTokenOnErrorListener);         } else {             Intent mainIntent = new Intent(mContext, MainActivity.class);             startActivity(mainIntent);         }     }  } 

GetTokenOnSuccessListener.java

public class GetTokenOnSuccessListener implements Response.Listener<JSONObject> {      //private Activity mActivity;     private Context mContext;     private ConfigTable mConfigTable;     private int mSuccess = 0;     private String mMessage = "";      public GetTokenOnSuccessListener(Context context) {         //this.mActivity = context;         this.mContext = context;         this.mConfigTable = new ConfigTable(this.mContext);     }      @Override     public void onResponse(JSONObject response) {         try {             mSuccess = Integer.parseInt(response.get("success").toString());             mMessage = response.get("message").toString();              if (mSuccess == 1) {                 mConfigTable.setAuthToken(response.get("message").toString());                 Intent mainIntent = new Intent(mContext, MainActivity.class);                 mContext.startActivity(mainIntent);                 ((SplashActivity) mContext).finish();             } else {                 Toast.makeText(mContext, "Lol access denied, could not retrieve token from server.", Toast.LENGTH_SHORT).show();             }           } catch (JSONException e) {             e.printStackTrace();             Toast.makeText(mContext, "Lol access denied, could not retrieve token from server.", Toast.LENGTH_SHORT).show();         }     } } 

GetTokenOnErrorListener.java

public class GetTokenOnErrorListener implements Response.ErrorListener {      private Context mContext;      public GetTokenOnErrorListener(Context context) {         this.mContext = context;     }      @Override     public void onErrorResponse(VolleyError error) {         Utils.showNetworkResponse(mContext, error);     } } 

Okay now I moved the response listeners to their own separate classes based on something I read online thinking it will resolve the leak but no it did not. I added code to cancel all pending requests onDestroy() based on the request's tag but still I had memory leaks.

This is just my splash activity and the leaks here are small, I have a feeling it's because I call finish() but I don't get that because I call it after the request has been completed successfully. All my other activities have similar codes but leak more memory as much as 11mb.

So my question is has anyone worked with the volley library? How do I use it and avoid memory leaks?

Using this version:

compile 'com.android.volley:volley:1.0.0' 

3 Answers

Answers 1

Please update to latest volley version they have fixed memory leaks. 'com.android.volley:volley:1.1.0-rc1'

https://github.com/google/volley/releases/tag/1.1.0-rc1

Answers 2

It's not enough just to "Move response listeners to their own separate classes". Your listeners have strong references to the Activity (mContext), introducing a leak during the request. It means that your Activity can't be garbage collected, while the request is ongoing. It's not really a Volley's fault, but rather a natural way of things.

You couple of options in your case:

1) Pass a WeakReference<Context> to your listeners, instead a strong reference to Context. This way you won't introduce a leak and will have to check if this referenced Context isn't yet null, when you try to access it. But I'd rather go for the 2nd option.

2) Set mContext to null in listeners, when Activity's onDestroy() is called. And perform null check as well, when you are trying to do something with Context in listener. So as soon as Activity will be destroyed, you'll remove other strong references to it, allowing GC to collect it normally.

Answers 3

You are always creating a new activity. Please try this instead. Read more about it here: https://developer.android.com/reference/android/content/Intent.html#FLAG_ACTIVITY_CLEAR_TOP

Intent mainIntent = new Intent(mContext, MainActivity.class); mainIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); mContext.startActivity(mainIntent); 
Read More

Sunday, October 15, 2017

Memory usage in JVM profiler vs. Mac OS X Activity Monitor

Leave a Comment

I've been profiling my java application and have been confused about the reported memory usage of my application (run via eclipse). It's always very different to the memory usage reported by the profiler, and doesn't really even match itself.

The JVM flags for the application are:

-Xmx1G   -Xms1G 	  -XX:MaxMetaspaceSize=256M  -XX:CompressedClassSpaceSize=256M

This image shows that the reported memory of the process "java" is 1.67GB. When I double click on that process, the breakdown shows 1.15GB of "Real Memory Size" and the various other memory metrics.

Reported Mac OS X memory usage

Flight recorder shows that the application adheres to its 1GB heap size. I have carried out tests that show that it also adheres to its metaspace limits.

Flight Recorder memory usage

My question is two fold: 1) Any idea why reported memory usage is so different between the process (as reported by Mac OS X) and the profiler? 2) Any idea why there's a disparity between memory shown in Activity Monitor and the breakdown of the process memory?

1 Answers

Answers 1

1) Real memory is everything together: heap + stack + MetaSpace (formerly PermGen) + CompressedClassSpaceSize + etc. You limit the heap to 1GiB as shown by Flight Recorder. The OS shows everything together, not just the heap, that is where this disparity originates. It is not OS/JVM specific (i.e., try it on *nix, Windows, you will see the same).

2) That is OS specific. For Mac OS see this very detailed answer

Read More

Sunday, August 20, 2017

angularjs 1.5 : How to identify what is getting leaked and fix the leak?

Leave a Comment

Tested in chrome latest and other browsers. This page starts a timer() to refresh every 60 seconds. On init() and every refresh(), it gets data from the server and display the same in the page. We see that it leaks lot of MB every refresh.

  1. Now, how do I identify the specific objects and/or DOM Nodes that are being leaked

  2. Once I identify the object/Nodes from #1, how do I go about fixing the leaks ?

Are there any books, good tutorials that would cover the above for Angularjs 1.5 ?

2 Answers

Answers 1

You probably found https://developers.google.com/web/tools/chrome-devtools/memory-problems/ and http://www.dwmkerr.com/fixing-memory-leaks-in-angularjs-applications/ as there are no more detailed resource out there.

A DOM node can only be garbage collected when there are no references to it from either the page's DOM tree or JavaScript code. A node is said to be "detached" when it's removed from the DOM tree but some JavaScript still references it. Detached DOM nodes are a common cause of memory leaks.

  1. If you're not holding a reference of the timer but creating a new timer on every refresh - leak, solvable by reusing the $timeout

  2. Checkout - CTRL + F $scope is retained by a context for a closure. on second provided link. The use case explained there is so similar to one you're having. Further on in the article:

We can open the function and examine it for issues. There's an $http.get which has as closure which uses $scope, but alarmingly there is an $interval registered to run every 10 seconds, which is never deregistered. The interval callback uses another $http.get, with a closure that uses $scope. This is the problem.

If none of the above applies then here's the list of open issues in AngularJS having memory leak as a keyword:

https://github.com/angular/angular.js/issues?utf8=%E2%9C%93&q=is%3Aopen%20memory%20leak

Answers 2

I am not sure if this will help you are not(maybe you've already looked into it), but it is worth mentioning. I had a similar issue with a previous application where objects were continuously being duplicated during every ajax request. So from the load of the page i would be using about 50mb of memory, but after making 10-15 ajax calls the memory would sky rocket to >1gb.

I was able to identify and resolve the issue using chrome dev tools -> memory tab. Through here you are able to record allocation profiles of memory and get a heap snapshot. So, for your situation i might cut the timer down to 5 or 10 seconds for testing purposes, then run these profilers. You will be able to get a view of what methods are being called and at what cost.

Hope this helps.

Read More

Thursday, August 10, 2017

Android cache background process is increasing continuously

Leave a Comment

In my android application named "PriceDekho" the cache background process takes too much space. First when i start the application the application takes arround 30MB (I think its OK) but the problem is when i surfing the application pages then this size is increasing continuously upto (200 MB). This appliction "Cache background process" also varying with the mobile RAM size. If the mobile RAM size is 2GB then this application "Cache background process" size goes upto 500 to 700 MB.

My application is having only 5 to 6 screens. I just need to stabilize the cached background size.

How can i clear the application cached size? Please help.

enter image description here

enter image description here

2 Answers

Answers 1

It sounds like you have memory leaks which the Garbage Collector can not remove. For example if you need to have a reference to the Context from a non-context class which is never released there. Most of the time Android Studio will point those out but you can try to use LeakCanary and search for them.

Add the dependency

dependencies {    debugCompile 'com.squareup.leakcanary:leakcanary-android:1.5.1'  } 

and use it in your Application class. Create one if you don't have it already.

public class ExampleApplication extends Application {    @Override public void onCreate() {     super.onCreate();     if (LeakCanary.isInAnalyzerProcess(this)) {       // This process is dedicated to LeakCanary for heap analysis.       // You should not init your app in this process.       return;     }     LeakCanary.install(this);     // Normal app init code...   } } 

Answers 2

Cache background process surely varies with the RAM size as the system will allow more data to be cached if more memory is available.

However, the increasing pattern in memory usage by the application may either be due to memory leaks or huge objects being created in the background. The Garbage collector is not an all weather friend and may tend to ignore memory leaks due to programmatic mistakes.

As there is no code posted for review, some trivial questions to ask would be:

  • Is there a lot of image processing being done using bitmaps? If yes, are those bitmaps being recycled ?
  • Is your application using the context judiciously, that is avoiding usage of the application context, unless required ?
  • Are the listeners being unregistered, if any ?

    As suggested above, LeakCanary will surely be much useful in this case, surely more than the Android Monitor.

Read More

Wednesday, July 5, 2017

Finding memory leak

Leave a Comment

I have a web application that I wrote using a lot of different 3rd party components, a CMS and of course my code. For some reason I get out of memory exception.

Script threw an exception: Out of memory

I tried to find out what is going on. This is what I've found:

  • I ran the test with 50 threads to call 15 pages of my web-application. Memory seems fine. The IIS process is using only 400 MB of RAM

  • I've added a space in web.config and suddenly my IIS process started to grow to more than a GB in 30 minutes. Visual studio could not take snapshot of my memory since it is too big (really?!) So I've installed ANTS memory profiler but it says that my application is using only around 300 MBANTS only 300 MB

IIS process takes 1 GB [1]: https://i.stack.imgur.com/Ig8pY.png

I stopped the test after some minutes but the memory has not released.

(ANTS profiler stopped working so I've restarted it) 422MB after release IIS 1.2GB Summary 4MB of strings

It doesn't seem like the application is using 100-200MB memory specially that I am using output caching for my controllers. What I don't understand is why memory consumed by IIS is growing all the time and what is wrong

Update

My application has been restarted automatically with a crash in W3WP causing IIS to release the memory while my stress was not running for a while:

Application: w3wp.exe Framework Version: v4.0.30319 Description: The process was terminated due to an internal error in the .NET Runtime at IP 5A3A86F1 (5A0F0000) with exit code 80131506.

and

Faulting application name: w3wp.exe, version: 10.0.15063.0, time stamp: 0xacce422f Faulting module name: clr.dll, version: 4.7.2098.0, time stamp: 0x59028d36 Exception code: 0xc0000005 Fault offset: 0x002b86f1 Faulting process id: 0x50a4 Faulting application start time: 0x01d2ee688f323893 Faulting application path: C:\WINDOWS\SysWOW64\inetsrv\w3wp.exe Faulting module path: C:\Windows\Microsoft.NET\Framework\v4.0.30319\clr.dll Report Id: 4362ddc5-f8d7-4441-8916-3830f9268b3a Faulting package full name: Faulting package-relative application ID:

enter image description here

Update 2

I ran DebugDiag and I've stress tested the site until it consumed around 3.5 GB of my RAM.

enter image description here

And Chakra is a Microsoft's library.

enter image description here enter image description here

So now I have 2 questions.

  1. Is it the ChakraCore that has leak or is it the one that is using/allocating it? How to define which library?

2- It says 27,000 allocations. Does it mean that there are still 27,000 in the memory or some of them might be allocated and then disposed?

3- It still doesn't tell me anything about the rest of 3GB of consumed RAM. it i only 600 MB in total (private+virtual).

4 Answers

Answers 1

In your analysis, I see that the .net analysis is not done correctly. Are you doing analysis in the same machine where you have captured the memory dump ?

For debugdiag to work correctly, you have to have the same version of .net framework (of the application) installed on the analyzing machine as well.

Also Please do not do native memory leak dump like this ,unless it is not figured out unmanaged leak.From the analysis of yours, it looks like this is managed leak.

When you changed the web.config file,it causes an Application domain unload and reload

Let's do step by step

  1. Using DebugDiag(capture consecutive hang dumps)
    • Launch DebugDiag Collection and Go to the Processes tab debugdiag process tab
    • Start your stress test
    • check the memory usage and once it reaches say 1 GB,capture a hang dump
      • right click on the w3wp.exe process
      • choose the option Create Full Memory dump capture full memory hang dump
    • Capture another dump at 2 GB and one at 3.5 GB
    • You should have dumps captured in the folder C:\ProgramFiles\DebugDiag\Logs\Misc\
    • Right click on the dump file and choose the option Analyse .NET Memory Issue Analyse .net memory issue

Now compare the analysis of each dump file(1 GB,2 GB, 3.5 GB), it should tell you which .NET objects are increasing and not getting garbage collected.

In the memory analysis, you should see CLR Information****,.NET GC Heap Information ,Most memory Consuming .NET Objects etc like below. This will come if your .net symbols are correctly identified by debugdiag analysis

CLR Information  CLR version = 4.6.1648.0  Microsoft.Diagnostics.Runtime version = 0.9.2.0 .NET GC Heap Information Number of GC Heaps: 4  Heap Size 0x4001ce8 (67,116,264)  Heap Size 0x3d5cca0 (64,343,200)  Heap Size 0x3f8b0d0 (66,629,840)  Heap Size 0x3ccb0d0 (63,746,256)  GC Heap Size 249.71 MBytes   Total Commit Size  249 MB  Total Reserved Size    17158 MB   40 most memory consuming .NET object types  System.Char[]   193.01 MBytes    (12450 objects ) Free      45.21 MBytes    (4760 objects ) System.String      1.56 MBytes    (18072 objects )  ==============trimmed out ======================= 

DebugDaig Automated analysis should give following

  1. **Errors or Warnings **- pay close attention to warning or errors displayed by debugdiag analysis on the top of the report.
  2. .NET GC Heap Information - Total Commit Size - This will roughly equal to your .net memory usage.
  3. 40 most memory consuming .NET object types -This can be used to compare against your memory increase in consecutive dumps. This will tell you which objects are causing issue.Sometimes some objects you are not using at all will be coming and might be coming from some third party library.Or you will see objects which you yourself have created
  4. Top Objects in the Finalizer queue - This will give you any clue if your finalizer may be blocked .Objects.Some similar issues are discussed here and here
  5. Objects on the Large Object Heap - This causes memory fragmentation and large object heap contaisn objects which are more than 85K in size.
  6. Size of Cache, Datatables,Application domains,Dynamic assemblies etc. It's not a good idea to have large number of application domain in one process

Please note that sometimes the debugdiag automated analysis cannot figure out the root cause and needs manual analysis using windbg. DebugDiag analysis,please refer this video.

Hope this helps!

Answers 2

Since it appears you can reproduce your issue, sometimes the simplest approach is to remove things you think might be the root cause, and test again (unless you need a lot of time to see if it grows a lot or not?)

At some point the bug will stop happening, and you'll know what bit of code was responsible.

However, depending on your code base, it's not always easy to remove code and still have something that you can test (i.e. without crashing the application).

Answers 3

When it comes to fixing memory leaks there are two steps.

  1. Finding where the memory leak is.
  2. Fixing the memory leak.

Normally the first step is tricky. So, I would recommend to go ahead with ANTS memory profiler and first find what exact instances are growing.

Profiling an ASP.NET application on IIS

In your question you have shown the class list result which includes even classes with system namespace. To clean up the noise, you can select "Show Only Classes with source" option.

enter image description here

Then follow the follwing steps.

  1. Take a base snapshot before you perform any operations.
  2. Perform the operations you suspect that have memory leaks.
  3. Take couple of more snapshots until you get a fairly stable snapshot.
  4. Compare the last snapshot with the base and see what instances are growing.

Answers 4

You mentioned "I've added a space in web.config and suddenly my IIS process started to grow to more than a GB in 30 minutes". In which web.config tag have you appended this space. What part of your code uses it. Is that part of your code unable to handle some exception without causing memory leak. Use PerfView (Dump GC heap) to analyze the dump. This can exactly tell, the object of what kind is taking up this much of memory. In older versions of .net, it would be objects on large object heap (big arrays) or open and mis-handled db connections and files.

https://channel9.msdn.com/Series/PerfView-Tutorial/Tutorial-10-Investigating-NET-Heap-Memory-Leaks-Part1-Collecting-the-data

https://channel9.msdn.com/Series/PerfView-Tutorial/Tutorial-11-Investigating-NET-Heap-Memory-Leaks-Part2-Analyzing-the-data

Read More

Thursday, June 15, 2017

How can I automatically test for memory leaks in Node?

Leave a Comment

I have some code in a library that has in the past leaked badly, and I would like to add regression tests to avoid that in the future. I understand how to find memory leaks manually, by looking at memory usage profiles or Valgrind, but I have had trouble writing automatic tests for them.

I tried using global.gc() followed by process.memoryUsage() after running the operation I was checking for leaks, then doing this repeatedly to try to establish a linear relationship between number of operations and memory usage, but there seems to be noise in the memory usage numbers that makes this hard to measure accurately.

So, my question is this: is there an effective way to write a test in Node that consistently passes when an operation leaks memory, and fails when it does not leak memory?

One wrinkle that I should mention is that the memory leaks were occurring in a C++ addon, and some of the leaked memory was not managed by the Node VM, so I was measuring process.memoryUsage().rss.

2 Answers

Answers 1

Automating and logging information to test for memory leaks in node js.

  • There is a great module called memwatch-next.

    npm install --save memwatch-next

Add to app.js:

const memwatch = require('memwatch-next');  // ...  memwatch.on('leak', (info) => {    // Some logging code...    console.error('Memory leak detected:\n', info); }); 

This will allow you to automatically measure if there is a memory leak.

  • Now to put it to a test:

Good tool for this is Apache jMeter. More information here.

If you are using http you can use jMeter to soak test the application's end points.

SOAK testing is done to verify system's stability and performance characteristics over an extended period of time, its good when you are looking for memory leaks, connection leaks etc.

  • Continuous integration software:

Prior to deployment to production if you are using a software for continuous integration like Jenkins, you can make a Jenkins job to do this for you, it will test the application with parameters provided after the test will ether deploy the application or report that there is a memory leak. ( Depending on your Jenkins job configuration )

Hope it helps, update me on how it goes;

Good luck,

Answers 2

Given some arbitrary program, is it always possible to determine if it will ever terminate? The halting problem describes this. Consider the following program:

function collatz(n){     if(n==1)         return;      if(n%2==0)         return collatz(n/2);     else         return collatz(3*n+1); } 

The same idea can be applied to data in memory. It's not always possible to identify what memory isn't needed anymore and can thus be garbage collected. There is also the case of the program being designed to consume a lot of memory in some situation. The only known option is coming up with some heuristic like you have done, but it will most likely result in false positives and negatives. It may be easier to determine the root cause of the leak so it can be corrected.

Read More

Sunday, March 19, 2017

Memory leak _ContiguousArrayStorage?

Leave a Comment

I'm new to swift.I'm running instrument tool for memory leaks.I found a leak "_ContiguousArrayStorage<String>"

Screen Shot of Instruments

Its leading to below part of the code

let myData = NSData(data: request.value!) let buffer = Array(UnsafeBufferPointer(start: UnsafePointer<CUnsignedChar>(myData.bytes), count: myData.length)) 

Screenshot of code leakage lines

Can anyone help me out?.

Anything wrong with above code?

Edit: Adding some more code.

let myData = NSData(data: request.value!) var buffer = Array(UnsafeBufferPointer(start: UnsafePointer<CUnsignedChar>(myData.bytes), count: myData.length))  let responseArray: [CUnsignedChar] = Array(buffer)  let responseValue = BluetoothCommunicationManager.sharedInstance.parseData(responseArray,length: myData.length).0  let responseName = BluetoothCommunicationManager.sharedInstance.parseData(responseArray,length: myData.length).1  NSNotificationCenter.defaultCenter().postNotificationName(responseName, object: request, userInfo: responseValue as [NSObject : AnyObject]) 

The parseData method of the singleton class returns NSMutableDictionary.

func parseData(responseData: [CUnsignedChar]) -> NSMutableDictionary {         let infoDictionary = NSMutableDictionary()         let subIndexValue = Int(responseData[5])         infoDictionary.setValue(subIndexValue, forKey: KEY_SUB_INDEX)         return responseData } 

Thanks in advance.

1 Answers

Answers 1

It looks like you are trying to convert the NSData to an array of CUnsignedChar. You don't need to use UnsafeBufferPointer or UnsafePointer to do that conversion. I suspect your use of the unsafe pointers is the root cause of your memory leak.

You can just create the array by passing it a Data object instead of an NSData object. Try this instead:

let myData = NSData(data: request.value!) as Data let responseArray = [CUnsignedChar](myData)  let responseValue = BluetoothCommunicationManager.sharedInstance.parseData(responseArray, length: responseArray.count).0  let responseName = BluetoothCommunicationManager.sharedInstance.parseData(responseArray, length: responseArray.count).1 
Read More

Monday, April 11, 2016

Will multiple presentViewController method calls throughout the view controllers lead to memory leak in iOS?

Leave a Comment

I know there has been a lot of discussions occurred related to this topic. But in all discussions all have discussed with 2 view controllers (A&B). My scenario is similar but different.

What will happen when there are multiple view controllers like A,B,C,D. So the presenting flow moves as ,

View controller A (Home) presents View controller B(List). Then from View controller B presents View Controller C (Details).Then from View Controller C presents View Controller D(Advanced Details). Then from View Controller D presents View Controller A , in order to navigate straight to Home !!!

What is the best practice for that ???

3 Answers

Answers 1

Not knowing your project structure and details of how you will display A,B,C,D,E,F and then from F back to A, I would take a wild guess and say that it may lead to a memory leak depending on what design patterns you employ to your UIViewControllers. As commented by @CaptJak in your questions, it has hard to tell if, how and when it will cause a memory leak, especially if you use delegation pattern to pass data around view controllers.

Personally, when I do complicated flows such as presenting multiple UIViewControllers and find myself needing to go back a few screens, I will neither pop the views on the stack up until the one I want is on top of the stack (if you are using navigation controller), dismiss view controller if it is presented modally, or unwind segues if I use them. The risk here might be the view controller's memory may have deallocated.

I would have commented but I don't have enough reputation. Take my answer with a grain of salt as I am a still quite fresh in iOS development.

EDIT: Thank you for the details provided in your app flow. Since you could use presentViewController, I am assuming you are running on a NavigationController? If that is the case, I would use popToViewController or popToRootViewController (if A is your root view controller) for this case instead of presenting A from D again. If A is presented from D again, I am guessing that you will have 2 instances of A in your VC stack which may lead to memory leak.

PopToViewController method

NSArray arrayOfVCs = self.navigationController.viewControllers; for(UIViewController *currentVC in arrayOfVCs) {    if([currentVC isKindOfClass:[ViewControllerA class])    {       [self.navigation.controller popToViewController:currentVC animated:YES]    } } 

PopToRootViewController method (assuming A is your root view in navigation controller)

[self.navigationController popToRootViewControllerAnimated:YES] 

Answers 2

I do believe it is possible to command + drag from a UIButton (or whatever else you are using to control your flow) to the view controller that you next want to present, so as to navigate properly. Then, you let go and select whatever method of presentation you want, and when you try it, it should work. I am assuming you use XCode for this, and I am not sure for other development applications.

This is designed to prevent a memory leak from occurring, but do note that you will have to create separate files for each separate view controller. Other manual forms of switching may result in memory leaks, depending on the contents of your situation.

Answers 3

Nothing bad if you will display newly created A view controller.

Read More