Can Ürek Can Ürek - 3 years ago 199
Objective-C Question

Xcode NSMutableData replaceBytesInRange CPU usage

I am writing an Mp3 player. I am downloading mp3 files from server. Files are encrypted. Encrypt method of my customer is very easy. They just insert a single bit per X byte. Like 323 in code. But decryption process take very long time. And CPU usage is huge? Why? And what can I do?

_mappedData = [[NSMutableData dataWithMappedContentsOfFile:_cachedPath] mutableCopy];

Singleton *singleton = [Singleton sharedSingleton];

NSLog(@"Decryption started");

if(singleton.playerMode == PLAYERMODELISTEN)
{
int i = 323;
while (i < [_mappedData length]) {
[_mappedData replaceBytesInRange:NSMakeRange(i, 1) withBytes:NULL length:0];
//CFDataDeleteBytes((CFMutableDataRef)_mappedData, CFRangeMake(i, 1000));
i += 323;
}
}


[General dismissGlobalHUD];

NSLog(@"Decryption completed");

Answer Source

Finally i solve that issue myself.

NSMutableData *decryptedData = [[NSMutableData alloc] init];

  NSUInteger length = [_mappedData length];
  NSUInteger chunkSize = 500;
  NSUInteger offset = 0;

  do {
      NSUInteger thisChunkSize = length - offset > chunkSize ? chunkSize : length - offset;
      NSData* chunk = [NSData dataWithBytesNoCopy:(char *)[_mappedData bytes] + offset
                                           length:thisChunkSize
                                     freeWhenDone:NO];
      offset += (thisChunkSize + 1);

      [decryptedData appendData:chunk];

  } while (offset < length);

  _mappedData = decryptedData;

That's my solution. Working very fast.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download