NSSortDescriptor用数字作为字符串排序?

时间:2012-03-30 13:30:32

标签: objective-c ios ios5

有一个充满字典的数组喜欢这个:

(
   { order = "10";
     name = "David"
   };
   { order = "30";
     name = "Jake";
   };
   { order = "200";
     name = "Michael";
   };
)

当我像下面的代码一样使用NSSortDescriptor时,它只对第一个字符进行排序,因此200低于30.我当然可以将“order”对象更改为NSNumber而不是字符串,它可以工作。但有没有办法将字符串排序为int值而不更改源对象?

NSSortDescriptor *descriptor = [[NSSortDescriptor alloc] initWithKey:@"norder"  ascending:YES];
[departmentList sortUsingDescriptors:[NSArray arrayWithObjects:descriptor,nil]];

更新

感谢bandejapaisa。

这是适用于iOS 5的工作版(Xcode,其中包括编译)。

NSArray *sortedArray;
sortedArray = [departmentList sortedArrayUsingComparator:(NSComparator)^(id a, id b) {
    NSNumber *num1 = [NSNumber numberWithInt:[[a objectForKey:@"norder"] intValue]];
    NSNumber *num2 = [NSNumber numberWithInt:[[b objectForKey:@"norder"] intValue]];

    return [num1 compare:num2];
}];
departmentList = [sortedArray mutableCopy];

3 个答案:

答案 0 :(得分:10)

使用NSNumber是过度的。通过执行以下操作,您可以节省大量开销:

NSArray *sortedArray = [someArray sortedArrayUsingComparator:^(id obj1, id obj2) {
    return (NSComparisonResult) [obj1 intValue] - [obj2 intValue];
}];

答案 1 :(得分:7)

可能使用比较器排序,或者使用其他排序方法之一:

NSArray *sortedArray = [someArray sortedArrayUsingComparator:^(id obj1, id obj2) {
  NSNumber *num1 = [NSNumber numberWithInt:[obj1 intValue]];
  NSNumber *num2 = [NSNumber numberWithInt:[obj2 intValue]];
  return (NSComparisonResult)[rank1 compare:num2];
}];

答案 2 :(得分:0)

所有上述方法都需要掌握基础知识才能实现,但对于新手我建议最简单的方法是使用本机块方法,希望这有帮助

 protected Dialog onCreateDialog(int id) {

    if (id == CONTEXT_MENU_ID) {
        return iconContextMenu.createMenu();
    }
    return super.onCreateDialog(id);
}

@SuppressWarnings("deprecation")
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {

    if (resultCode != RESULT_OK)
        return;

    switch (requestCode) {
        case PICK_FROM_CAMERA:
            doCrop();

            break;

        case PICK_FROM_FILE:
            mImageCaptureUri = data.getData();
            doCrop();

            break;

        case CROP_FROM_CAMERA:
            Bundle extras = data.getExtras();

            if (extras != null) {
                SelectedImage = extras.getParcelable("data");

                ByteArrayOutputStream baos = new ByteArrayOutputStream();
                SelectedImage.compress(Bitmap.CompressFormat.JPEG, 100, baos);
                imageData = baos.toByteArray();
                image = Base64.encodeBytes(imageData);
                filename = "img_" + System.currentTimeMillis();

                imageView.setImageBitmap(SelectedImage); //setting the image

            } else {
                image = "";
            }

            File f = new File(mImageCaptureUri.getPath());

            if (f.exists())
                f.delete();

            break;
    }
}

private void doCrop() {

    final ArrayList<CropOption> cropOptions = new ArrayList<CropOption>();

    Intent intent = new Intent("com.android.camera.action.CROP");
    intent.setType("image/*");

    List<ResolveInfo> list = getPackageManager().queryIntentActivities(intent, 0);

    int size = list.size();

    if (size == 0) {
        Toast.makeText(this, "Cannot find image cropping application", Toast.LENGTH_SHORT).show();

        return;
    } else {
        intent.setData(mImageCaptureUri);

        intent.putExtra("outputX", 200);
        intent.putExtra("outputY", 200);
        intent.putExtra("aspectX", 1);
        intent.putExtra("aspectY", 1);
        intent.putExtra("scale", true);
        intent.putExtra("return-data", true);

        if (size == 1) {

            Intent i = new Intent(intent);
            ResolveInfo res = list.get(0);
            i.setComponent(new ComponentName(res.activityInfo.packageName, res.activityInfo.name));
            startActivityForResult(i, CROP_FROM_CAMERA);

        } else {
            for (ResolveInfo res : list) {

                final CropOption co = new CropOption();
                co.title = getPackageManager().getApplicationLabel(res.activityInfo.applicationInfo);
                co.icon = getPackageManager().getApplicationIcon(res.activityInfo.applicationInfo);
                co.appIntent = new Intent(intent);
                co.appIntent.setComponent(new ComponentName(res.activityInfo.packageName, res.activityInfo.name));
                cropOptions.add(co);
            }

            CropOptionAdapter adapter = new CropOptionAdapter(getApplicationContext(), cropOptions);

            AlertDialog.Builder builder = new AlertDialog.Builder(this);
            builder.setTitle("Choose Crop App");
            builder.setAdapter(adapter,
                    new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int item) {
                            startActivityForResult(
                                    cropOptions.get(item).appIntent,
                                    CROP_FROM_CAMERA);
                        }
                    });

            builder.setOnCancelListener(new DialogInterface.OnCancelListener() {
                @Override
                public void onCancel(DialogInterface dialog) {

                    if (mImageCaptureUri != null) {
                        getContentResolver().delete(mImageCaptureUri, null, null);
                        mImageCaptureUri = null;
                    }
                }
            });

            AlertDialog alert = builder.create();
            alert.show();
        }
    }
}

快乐编码......